在使用 Form.List 组件时,可以通过 Form.Listname 属性来指定数据源的字段名,然后通过 Form.Listchildren 属性来定义渲染每行数据的内容。

以下是一个示例代码,演示如何使用 Form.List 自动渲染每行数据:

import { Form, Input, Button } from 'antd';

const MyForm = () => {
  const onFinish = (values) => {
    console.log('Form values:', values);
  };

  return (
    <Form name="myForm" onFinish={onFinish}>
      <Form.List name="data">
        {(fields, { add, remove }) => (
          <>
            {fields.map((field, index) => (
              <Form.Item key={field.key}>
                <Form.Item
                  {...field}
                  label={`Row ${index + 1}`}
                  name={[field.name, 'value']}
                  fieldKey={[field.fieldKey, 'value']}
                  rules={[{ required: true, message: 'Value is required' }]}
                >
                  <Input placeholder="Enter value" />
                </Form.Item>
                {fields.length > 1 && (
                  <Button type="danger" onClick={() => remove(field.name)}>
                    Remove
                  </Button>
                )}
              </Form.Item>
            ))}
            <Form.Item>
              <Button type="dashed" onClick={() => add()} block>
                Add Row
              </Button>
            </Form.Item>
          </>
        )}
      </Form.List>
      <Form.Item>
        <Button type="primary" htmlType="submit">
          Submit
        </Button>
      </Form.Item>
    </Form>
  );
};

export default MyForm;

在上述代码中,我们在 Form.List 中使用了一个函数作为子元素,该函数接收两个参数 fields{ add, remove }fields 是一个数组,每个元素代表一个数据行,我们可以通过 fields.map 来渲染出每行数据的内容。每个数据行都包含一个 Form.Item,其中包含了一个 Input 组件用于输入数据的值。addremove 函数分别用于添加和删除数据行。

当点击 "Add Row" 按钮时,会调用 add 函数来添加一行数据。当点击 "Remove" 按钮时,会调用 remove 函数来删除对应的数据行。

最后,我们在 onFinish 回调中可以获取到表单的所有值,包括每行数据的值。

注意:以上示例使用的是 Ant Design 的 FormInputButton 组件,你可以根据自己的需求来替换为其他组件

ReactFC的组件 FormList 怎么通过 FormList 实现自动渲染出每行数据

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

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