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

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

1个答案

1

In Ant Design 4, Form.List is a component used for handling dynamic form items. If you want to dynamically set values in Form.List using the setFieldsValue method, you need to properly manage the form's data structure to ensure that the data paths match the form field paths.

Step 1: Creating Form and Form.List

First, you need to have a basic structure using Form and Form.List. For example:

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;

Step 2: Using setFieldsValue

When setting values in Form.List, you must provide the complete path and value. For example, to set the first user's name:

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

Example Illustration

Assume you have a button to trigger the initial value setting function:

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

This button's click event calls the setInitialValues function, which uses setFieldsValue to set the first user's name to "John".

Important Notes

  1. Ensure your data structure matches the name attribute in Form.Item.
  2. Handle more complex data structures when Form.List is nested multiple layers or contains various input types.

By following these steps, you should be able to dynamically set form field values in Ant Design 4's Form.List.

2024年8月9日 20:41 回复

你的答案