Antd Form中initialValues动态content字段无法填充问题求助
解决Ant Design Form.List无法填充content数组数据的问题
你的问题出在Form.List中Form.Item的name属性配置错误,导致无法正确匹配initialValues里的content数组结构。以下是具体修复方案:
问题核心
API返回的content是包含para字段的对象数组,但你当前的Form.Item使用了固定的name={["name"]},这和数据结构不匹配,无法读取initialValues中的段落内容。
修复后的代码
修改Form.List内部的Form.Item配置,将name属性改为[name, 'para'],同时可完善编辑交互(添加/删除按钮):
<Form.List name="content"> {(fields, { add, remove }, { errors }) => { return ( <> {fields.map(({ key, name, ...restField }) => ( <div key={key} style={{ display: 'flex', gap: '10px', marginBottom: '10px' }}> <Form.Item {...restField} name={[name, 'para']} // 关键修改:对应content数组项的para字段 rules={[ { required: true, message: "This field is required!", }, ]} style={{ flex: 1 }} > <TextArea rows={10} placeholder="Add Article Content" /> </Form.Item> <Button onClick={() => remove(name)} danger>删除</Button> </div> ))} <Button type="dashed" onClick={() => add({ para: '' })}>添加段落</Button> {errors && errors.map((error, index) => ( <div key={index} style={{ color: '#ff4d4f' }}>{error.message}</div> ))} </> ); }} </Form.List>
关键说明
name={[name, 'para']}:这里的name是Form.List自动生成的数组索引(0、1、2...),结合para字段名,能精准匹配initialValues中content数组里每个对象的para属性,实现数据自动填充。...restField:传递Form.List内部状态(如校验状态),保障表单校验功能正常。- 新增的添加/删除按钮:完善文章段落的编辑交互,符合可编辑表单的需求。
额外提示
确保initialValues中的content结构与API返回完全一致(每个元素包含para字段),Form.List才能正确识别并渲染对应数量的TextArea。
内容的提问来源于stack exchange,提问作者program_bumble_bee
相关产品推荐
相关产品推荐

