Form.List 组件是 Ant Design 中用于动态增删表单项的组件,它可以实现双向绑定功能。

要实现 Form.List 的双向绑定,需要以下步骤:

  1. 在 Form 组件中定义一个表单项数组的初始值,例如:
const [form] = Form.useForm();
form.setFieldsValue({
  items: [{ name: 'Apple' }, { name: 'Banana' }, { name: 'Orange' }],
});
  1. 在 Form.List 组件中,使用 name 属性指定绑定的表单字段名称,例如:
<Form.List name="items">
  {(fields, { add, remove }) => (
    <>
      {fields.map((field, index) => (
        <Form.Item
          key={field.key}
          label={`Item ${index + 1}`}
          {...field}
          fieldKey={[field.fieldKey, 'name']}
          rules={[{ required: true, message: 'Missing item name' }]}
        >
          <Input placeholder="Item name" />
        </Form.Item>
      ))}
      <Button onClick={() => add()} style={{ marginTop: '10px' }}>
        Add Item
      </Button>
    </>
  )}
</Form.List>
  1. 在提交表单时,可以通过 form.getFieldsValue().items 获取到绑定的表单项数组的最新值。

以上就是使用 Form.List 组件实现双向绑定的基本步骤


原文地址: http://www.cveoy.top/t/topic/iX0r 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录