官方地址:https://ant.design/components/form-cn/#components-form-demo-dynamic-form-item
基础Demo
import { Form, Input, Button, Space } from 'antd';
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';
const Demo = () => {
const onFinish = values => {
console.log('Received values of form:', values);
};
return (
<Form name="dynamic_form_nest_item" onFinish={onFinish} autoComplete="off">
<Form.List name="users">
{(fields, { add, remove }) => (
<>
{fields.map(({ key, name, fieldKey, ...restField }) => (
<Space key={key} style={{ display: 'flex', marginBottom: 8 }} align="baseline">
<Form.Item
{...restField}
name={[name, 'first']}
fieldKey={[fieldKey, 'first']}
rules={[{ required: true, message: 'Missing first name' }]}
>
<Input placeholder="First Name" />
</Form.Item>
<Form.Item
{...restField}
name={[name, 'last']}
fieldKey={[fieldKey, 'last']}
rules={[{ required: true, message: 'Missing last name' }]}
>
<Input placeholder="Last Name" />
</Form.Item>
<MinusCircleOutlined onClick={() => remove(name)} />
</Space>
))}
<Form.Item>
<Button type="dashed" onClick={() => add()} block icon={<PlusOutlined />}>
Add field
</Button>
</Form.Item>
</>
)}
</Form.List>
<Form.Item>
<Button type="primary" htmlType="submit">
Submit
</Button>
</Form.Item>
</Form>
);
};
ReactDOM.render(<Demo />, mountNode);
值
得到值的格式见上图,再组装为需求的格式
用法
常用函数
- add : 新增一项
add(参数一,参数二)
参数一:defaultValue ,即默认值
参数二: insertIndex,新增的坐标。0为最上面,不填即为按顺序向下增加
-move: 移动某一项
move(参数一,参数二)
参数一:from ,即把谁移动,填写坐标
参数二: to,移动到哪里,填写坐标 - remove: 删除某一项或某几项
remove(参数一)
参数一:index ,即把谁删除,填写坐标或坐标集合