mirror of
https://github.com/ant-design/ant-design.git
synced 2024-12-04 17:09:46 +08:00
ed37b80d11
* Update dynamic-form-items.md 原来的代码只有在使用Space包裹多个Form.Item的时候可以跑起来,如果把Space换成div或者其它组件,点击Add Field之后,因为多个Form.Item 通过 {...restField} 指定了相同的key,浏览器会报 Encountered two children with the same key, `0`. Keys should be unique so that components maintain their identity across updates. 换成这种restField的写法可以避免这个问题,让不使用Space包裹多个Form.Item的场景也能跑通不报错。 * Update components/form/demo/dynamic-form-items.md Co-authored-by: afc163 <afc163@gmail.com> Co-authored-by: afc163 <afc163@gmail.com>
70 lines
2.0 KiB
Markdown
70 lines
2.0 KiB
Markdown
---
|
|
order: 4.1
|
|
title:
|
|
zh-CN: 动态增减嵌套字段
|
|
en-US: Dynamic Form nest Items
|
|
---
|
|
|
|
## zh-CN
|
|
|
|
嵌套表单字段需要对 `field` 进行拓展,将 `field.name` 和 `field.fieldKey` 应用于控制字段。
|
|
|
|
## en-US
|
|
|
|
Nest dynamic field need extends `field`. Pass `field.name` and `field.fieldKey` to nest item.
|
|
|
|
```jsx
|
|
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);
|
|
```
|