---
name: "Form"
mode: "component"
versionRequirements:
  - { name: "@ray-js/ray", version: "0.5.10" }
title: "Form - 表单"
---

## Form

> [VERSION] @ray-js/ray >= 0.5.10

### 描述

表单容器，用于收集并提交其内部控件的输入值。

### 属性

| 属性 | 类型 | 必填 | 默认值 | 描述 |
| --- | --- | --- | --- | --- |
| `onSubmit` | `(event: FormSubmitEvent) => void` | 否 | - | 携带 form 中的数据，提交时触发 |
| `onReset` | `(event: FormResetEvent) => void` | 否 | - | 表单重置时触发 |

### 引用对象

##### `interface` FormSubmitEvent

| 属性 | 类型 | 描述 |
| --- | --- | --- |
| `type` | `"submit"` | 事件类型 |
| `detail` | `FormSubmitDetail` | 事件数据，通过 detail.value 获取表单数据 |

##### `interface` FormResetEvent

| 属性 | 类型 | 描述 |
| --- | --- | --- |
| `type` | `"reset"` | 事件类型 |

##### `interface` FormSubmitDetail

| 属性 | 类型 | 描述 |
| --- | --- | --- |
| `value` | `Record<string, unknown>` | 表单数据，key 为各表单控件的 name |

##### `interface` BaseEvent

| 属性 | 类型 | 描述 |
| --- | --- | --- |
| `type` | `string` | 事件类型 |
| `timeStamp` | `number` | 页面打开到触发事件所经过的毫秒数 |
| `target` | `Target` | 触发事件的源组件 |
| `currentTarget` | `Target` | 当前组件的一些属性值集合 |
| `mark` | `any` | 事件标记数据 |

##### `interface` Target

| 属性 | 类型 | 描述 |
| --- | --- | --- |
| `id` | `string` | 事件源组件的id |
| `dataset` | `Record<string, unknown>` | 事件源组件上的 `dataset` 自定义属性组成的集合 |


### 示例代码

#### 基础用法

```tsx
import React, { useState } from 'react';
import { Button, Input, Switch, View, Form, Text } from '@ray-js/ray';

export default function () {
  const [resultData, setResultData] = useState({});

  return (
    <View style={{ padding: '20px' }}>
      <Form
        onSubmit={(e) => {
          console.log('提交表单:', e.detail.value);
          setResultData(e.detail.value);
        }}
        onReset={() => {
          console.log('重置表单');
          setResultData({});
        }}
      >
        <View style={{ marginBottom: '16px' }}>
          <Text>开关:</Text>
          <Switch name="switch" />
        </View>
        <View style={{ marginBottom: '16px' }}>
          <Text>输入框:</Text>
          <Input name="input" placeholder="请输入" />
        </View>
        <Button formType="submit" type="primary">
          提交
        </Button>
        <Button formType="reset" style={{ marginTop: '10px' }}>
          重置
        </Button>
      </Form>
    </View>
  );
}
```
