P粉0468781972023-08-18 09:05:51
You need to update the name
and value
properties to include the full path to the nested field
<input name={`${key}.${nestedFieldName}`} // 包含嵌套字段的路径 value={getIn(values, `${key}.${nestedFieldName}`)} // 使用formik的getIn获取嵌套值 onChange={handleChange} placeholder={fieldObj.title} />
Your code only handles one level of nesting.
For deeper nesting, you need to render and process the nested fields recursively
{Object.entries(item[key]?.fields).map(([nestedFieldName, fieldObj]) => ( <div style={{ marginLeft: 20 }} key={nestedFieldName}> <p>{fieldObj.title}</p> <input name={`${key}.${nestedFieldName}`} value={getIn(values, `${key}.${nestedFieldName}`)} onChange={handleChange} placeholder={fieldObj.title} /> {fieldObj.fields && ( <div style={{ marginLeft: 20 }}> {Object.entries(fieldObj.fields).map(itemsRender)} </div> )} </div> ))}
Finally, do not use handleChange
to handle nested fields directly. Instead, use Formik's setFieldValue
to update the value of the nested field.
You can access setFieldValue
from the form object:
onChange={(e) => { form.setFieldValue(`${key}.${nestedFieldName}`, e.target.value); }}