javascript
import React, { useState } from 'react';
import { Form, Input, Switch, Button } from 'antd';
const Demo = () => {
const [switches, setSwitches] = useState({});
const onFinish = (values) => {
console.log('Received values of form: ', values);
};
return (
<Form
name="dynamic_form_item"
onFinish={onFinish}
autoComplete="off"
>
<Form.List name="list">
{(fields, { add, remove }) => (
<>
{fields.map((field, index) => (
<Form.Item
{...field}
name={[field.name]}
key={field.key}
fieldKey={field.fieldKey}
>
<Input placeholder="Input number" />
<Switch
checked={switches[field.name]}
onChange={(checked) => {
setSwitches({ ...switches, [field.name]: checked });
}}
/>
{fields.length > 1 ? (
<Button
onClick={() => {
remove(field.name);
setSwitches({ ...switches, [field.name]: undefined });
}}
>
Delete
</Button>
) : null}
</Form.Item>
))}
<Form.Item>
<Button type="dashed" onClick={() => add()}>
<PlusOutlined /> Add field
</Button>
</Form.Item>
</>
)}
</Form.List>
<Form.Item>
<Button type="primary" htmlType="submit">
Submit
</Button>
</Form.Item>
</Form>
);
};
export default Demo;
这个代码示例展示了如何使用Ant Design的Form和Form.List组件来创建一个可动态增减表单项的表单,并且每个表单项旁边都有一个Switch组件,这些Switch组件是受控的,即它们的状态会被保存在组件的状态中。当用户提交表单时,表单的数据以及Switch的状态都会被打印出来。