如果字段名称出现在道具中,如何设置 Formik InitialValues?

How to set Formik InitialValues if field name is coming in props?

我必须将 Formik 设置为

initialValues={{ location: initialValue }}>

字段名称 'key.location' 作为道具 'location' 传递。 如何将字段名称设置为 'key.location' 而不是 'location' ?

你可以做到

initialValues={{ "key.location": initialValue }}

你可能试过了

initialValues={{ key.location: initialValue }}

这会失败。只需将密钥设为字符串即可解决您的问题。

编辑 1:

如果该值作为名称为 location 的道具传递,您可以执行以下操作:

initialValues={{ [location]: initialValue }}
// or
initialValues={{ [props.location]: initialValue }}

Sandbox