2019-07-03 20:14:39 +08:00
---
order: 4
title:
zh-CN: 动态增减表单项
en-US: Dynamic Form Item
---
## zh-CN
2020-03-16 15:00:27 +08:00
动态增加、减少表单项。如果需要动态支持多项字段时,可以参考[此处](https://codesandbox.io/s/wonderful-lichterman-br63z)。
2019-07-03 20:14:39 +08:00
## en-US
2020-03-16 15:00:27 +08:00
Add or remove form items dynamically. You can ref [this example ](https://codesandbox.io/s/wonderful-lichterman-br63z ) if you want to support mutiple fields.
2019-07-03 20:14:39 +08:00
```jsx
2019-08-13 14:07:17 +08:00
import { Form, Input, Button } from 'antd';
2019-11-28 12:34:33 +08:00
import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';
2019-07-03 20:14:39 +08:00
const formItemLayout = {
labelCol: {
xs: { span: 24 },
sm: { span: 4 },
},
wrapperCol: {
xs: { span: 24 },
sm: { span: 20 },
},
};
const formItemLayoutWithOutLabel = {
wrapperCol: {
xs: { span: 24, offset: 0 },
sm: { span: 20, offset: 4 },
},
};
const DynamicFieldSet = () => {
const onFinish = values => {
console.log('Received values of form:', values);
};
return (
< Form name = "dynamic_form_item" { . . . formItemLayoutWithOutLabel } onFinish = {onFinish} >
< Form.List name = "names" >
{(fields, { add, remove }) => {
return (
< div >
{fields.map((field, index) => (
< Form.Item
{...(index === 0 ? formItemLayout : formItemLayoutWithOutLabel)}
label={index === 0 ? 'Passengers' : ''}
required={false}
key={field.key}
>
< Form.Item
{...field}
validateTrigger={['onChange', 'onBlur']}
rules={[
{
required: true,
whitespace: true,
message: "Please input passenger's name or delete this field.",
},
]}
2019-07-19 14:07:39 +08:00
noStyle
2019-07-03 20:14:39 +08:00
>
2020-03-30 21:23:05 +08:00
< Input placeholder = "passenger name" style = {{ width: ' 60 % ' } } / >
2019-07-03 20:14:39 +08:00
< / Form.Item >
{fields.length > 1 ? (
2019-11-28 12:34:33 +08:00
< MinusCircleOutlined
2019-07-03 20:14:39 +08:00
className="dynamic-delete-button"
2020-03-30 21:23:05 +08:00
style={{ margin: '0 8px' }}
2019-07-03 20:14:39 +08:00
onClick={() => {
remove(field.name);
}}
/>
) : null}
< / Form.Item >
))}
< Form.Item >
< Button
type="dashed"
onClick={() => {
add();
}}
style={{ width: '60%' }}
>
2019-11-28 12:34:33 +08:00
< PlusOutlined / > Add field
2019-07-03 20:14:39 +08:00
< / Button >
< / Form.Item >
< / div >
);
}}
< / Form.List >
< Form.Item >
< Button type = "primary" htmlType = "submit" >
Submit
< / Button >
< / Form.Item >
< / Form >
);
};
ReactDOM.render(< DynamicFieldSet / > , mountNode);
```
```css
.dynamic-delete-button {
cursor: pointer;
position: relative;
top: 4px;
font-size: 24px;
color: #999 ;
transition: all 0.3s;
}
.dynamic-delete-button:hover {
color: #777 ;
}
.dynamic-delete-button[disabled] {
cursor: not-allowed;
opacity: 0.5;
}
```
2019-12-25 17:12:36 +08:00
< style >
[data-theme="dark"] .dynamic-delete-button {
color: rgba(255,255,255,.45);
}
[data-theme="dark"] .dynamic-delete-button:hover {
color: rgba(255,255,255,.65);
}
< / style >