You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
124 lines
2.9 KiB
124 lines
2.9 KiB
5 years ago
|
---
|
||
|
order: 4
|
||
|
title:
|
||
|
zh-CN: 动态增减表单项
|
||
|
en-US: Dynamic Form Item
|
||
|
---
|
||
|
|
||
|
## zh-CN
|
||
|
|
||
|
动态增加、减少表单项。
|
||
|
|
||
|
## en-US
|
||
|
|
||
|
Add or remove form items dynamically.
|
||
|
|
||
|
```jsx
|
||
|
import { Form, Input, Icon, Button } from 'antd';
|
||
|
|
||
|
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.",
|
||
|
},
|
||
|
]}
|
||
|
inline
|
||
|
>
|
||
|
<Input placeholder="passenger name" style={{ width: '60%', marginRight: 8 }} />
|
||
|
</Form.Item>
|
||
|
{fields.length > 1 ? (
|
||
|
<Icon
|
||
|
className="dynamic-delete-button"
|
||
|
type="minus-circle-o"
|
||
|
onClick={() => {
|
||
|
remove(field.name);
|
||
|
}}
|
||
|
/>
|
||
|
) : null}
|
||
|
</Form.Item>
|
||
|
))}
|
||
|
<Form.Item>
|
||
|
<Button
|
||
|
type="dashed"
|
||
|
onClick={() => {
|
||
|
add();
|
||
|
}}
|
||
|
style={{ width: '60%' }}
|
||
|
>
|
||
|
<Icon type="plus" /> Add field
|
||
|
</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;
|
||
|
}
|
||
|
```
|