ant design框架Form.List使用示例
时间: 2023-09-02 12:11:55 浏览: 64
Ant Design 的 Form.List 组件可以用来动态添加和删除表单项。下面是一个示例:
```jsx
import { Form, Input, Button } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
const Demo = () => {
const onFinish = (values) => {
console.log('Received values of form:', values);
};
return (
<Form name="dynamic_form_item" onFinish={onFinish}>
<Form.List name="users">
{(fields, { add, remove }) => (
<>
{fields.map((field) => (
<Form.Item
{...field}
name={[field.name, 'name']}
fieldKey={[field.fieldKey, 'name']}
rules={[{ required: true, message: 'Missing name' }]}
>
<Input placeholder="Name" />
</Form.Item>
))}
<Form.Item>
<Button type="dashed" onClick={() => add()} block icon={<PlusOutlined />}>
Add user
</Button>
</Form.Item>
</>
)}
</Form.List>
<Form.Item>
<Button type="primary" htmlType="submit">
Submit
</Button>
</Form.Item>
</Form>
);
};
export default Demo;
```
在这个示例中,我们创建了一个动态表单,可以添加和删除用户。`Form.List` 组件包含一个名为 `users` 的表单项数组,我们使用 `fields.map` 方法将每个表单项渲染为一个 `Form.Item` 组件,其中属性 `field` 用于绑定表单项数据。点击 `Add user` 按钮会使用 `add` 函数添加一个新的表单项,而每个表单项上的 `Remove` 按钮则会使用 `remove` 函数删除该项。最后,我们使用 `onFinish` 函数来处理表单提交。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)