AntD嵌套Form.List调用setFieldsValue后子输入框不渲染值求助
AntD嵌套Form.List调用setFieldsValue后最内层输入框不渲染问题
问题场景
在AntD中嵌套三层Form.List(外层为concatenations,内层每个项包含options Form.List),调用setFieldsValue时,表单监听器显示值已正确更新,但最内层options对应的输入框未渲染设置的值,其他层级输入框正常。
问题原因
最内层Form.List的name使用了手动拼接的字符串路径(如concatenations[0]转成数组),而非使用外层Form.List提供的动态name参数构建路径,导致Form无法正确关联字段更新与输入框的渲染触发。
解决方案
- 基于外层Form.List的
name参数(数组形式的字段路径),动态构建内层Form.List的name路径 - 最内层Form.Item的name绑定到对应数组项的字段,确保字段路径完全匹配表单值结构
修改后的关键代码
import { Form, Input, Button } from 'antd'; const Demo = () => { const [form] = Form.useForm(); const handleDebug = () => { form.setFieldsValue({ concatenations: [ { name: "Test Concatenation", options: [ { label: "Option 1", value: "opt1" }, { label: "Option 2", value: "opt2" } ] } ] }); console.log('Current form values:', form.getFieldsValue()); }; return ( <Form form={form} layout="vertical"> <Form.List name="concatenations"> {(fields, { add, remove }) => ( <> {fields.map(({ key, name, ...restField }) => ( <div key={key} style={{ marginBottom: 16 }}> <Form.Item {...restField} name={[name, "name"]} label="Concatenation Name" rules={[{ required: true, message: 'Please enter name' }]} > <Input placeholder="Enter concatenation name" /> </Form.Item> {/* 内层options Form.List:使用外层name动态构建路径 */} <Form.List name={[...name, "options"]}> {(optionFields, { add: addOption, remove: removeOption }) => ( <> {optionFields.map(({ key: optKey, name: optName, ...optRestField }) => ( <div key={optKey} style={{ marginLeft: 24, marginBottom: 8 }}> <Form.Item {...optRestField} name={[optName, "label"]} label="Option Label" rules={[{ required: true, message: 'Please enter label' }]} > <Input placeholder="Enter option label" /> </Form.Item> <Form.Item {...optRestField} name={[optName, "value"]} label="Option Value" rules={[{ required: true, message: 'Please enter value' }]} > <Input placeholder="Enter option value" /> </Form.Item> <Button onClick={() => removeOption(optName)} type="text" danger> Remove Option </Button> </div> ))} <Button onClick={() => addOption()} type="dashed" style={{ marginLeft: 24 }}> Add Option </Button> </> )} </Form.List> <Button onClick={() => remove(name)} type="text" danger> Remove Concatenation </Button> </div> ))} <Button onClick={() => add()} type="dashed"> Add Concatenation </Button> </> )} </Form.List> <Button onClick={handleDebug} style={{ marginTop: 16 }}> DEBUG Set Value </Button> </Form> ); }; export default Demo;
核心说明
- 外层Form.List的
name参数是数组形式的字段路径(如['concatenations', 0]),通过[...name, "options"]构建内层Form.List的完整路径,确保Form能跟踪字段的动态变化 - 最内层Form.Item的
name使用内层Form.List提供的optName(如['concatenations', 0, 'options', 0])结合字段名(label/value),保证与setFieldsValue传入的结构完全匹配 setFieldsValue时保持嵌套数组结构,直接对应表单字段的层级
内容的提问来源于stack exchange,提问作者Juan Pedro Pont Vergés
相关产品推荐
相关产品推荐

