乐闻世界logo
搜索文章和话题

How to set value dynamically inside Form.List using setFieldsValue in Antd 4?

1 个月前提问
1 个月前修改
浏览次数4

1个答案

1

在Antd 4中,Form.List 是用来处理动态表单项的一个组件。如果你想在 Form.List 中使用 setFieldsValue 方法动态设置值,你需要正确地管理表单的数据结构,确保数据路径与表单的字段路径匹配。

步骤 1: 创建Form与Form.List

首先,你需要有一个使用 FormForm.List 的基本结构。例如:

jsx
import React from 'react'; import { Form, Input, Button } from 'antd'; const DynamicFieldSet = () => { const [form] = Form.useForm(); return ( <Form form={form} name="dynamic_form_nest_item" onFinish={onFinish} autoComplete="off"> <Form.List name="users"> {(fields, { add, remove }) => ( fields.map(({ key, name, ...restField }) => ( <Form.Item key={key} {...restField} name={[name, 'first']} rules={[{ required: true, message: 'Missing first name' }]} > <Input placeholder="First Name" /> </Form.Item> )) )} </Form.List> <Button type="primary" onClick={() => add()}>Add User</Button> <Button type="primary" htmlType="submit">Submit</Button> </Form> ); }; export default DynamicFieldSet;

步骤 2: 使用setFieldsValue

当你需要设置 Form.List 中的值,你必须提供完整的路径和值。例如,如果你想设置第一个用户的名字:

jsx
const setInitialValues = () => { form.setFieldsValue({ users: [ { first: 'John' } ] }); };

实例说明

假设你有一个按钮用来触发设置初始值的函数:

jsx
<Button type="button" onClick={setInitialValues}>Set John's Name</Button>

这个按钮的点击事件将调用 setInitialValues 函数,该函数利用 setFieldsValue 将表单中第一个用户的名字设置为 "John"。

注意事项

  1. 确保你的数据结构与Form.Item中的 name 属性保持一致。
  2. 你可能需要处理更复杂的数据结构,特别是当 Form.List 嵌套多层或包含多种类型的输入时。

通过以上步骤,你应该能够在Antd 4的 Form.List 中动态设置表单字段的值。

2024年8月9日 20:41 回复

你的答案