我想渲染一个带有 <FieldArray />
内嵌套字段的表单成分。但是当我根据索引创建表单字段时,我得到了我不想要的额外字段。如下图:
如您所见,Julia 和 28 应该位于同一行。但相反,我得到两行四个字段。空字段还会在键入时写入年龄和姓名值。我不明白为什么会发生这种情况。但我不想要它们。您可以在下面看到该组件的代码。我还创建了一个沙箱来处理它在这里 codesandbox .
注意:我想要这些嵌套字段,以便我的数组 friends: [{ name: "Julia" }, { age: "28" }]
的结构对这个问题很重要。
import React from "react";
import { Formik, Form, Field, FieldArray } from "formik";
// Here is an example of a form with an editable list.
// Next to each input are buttons for insert and remove.
// If the list is empty, there is a button to add an item.
const FriendList = () => (
<div>
<h1>Friend List</h1>
<Formik
initialValues={{ friends: [{ name: "Julia" }, { age: "28" }] }}
onSubmit={values =>
setTimeout(() => {
alert(JSON.stringify(values, null, 2));
}, 500)
}
render={({ values }) => (
<Form>
<FieldArray
name="friends"
render={arrayHelpers => (
<div>
{values.friends.map((friend, index) => (
<div key={index}>
<Field name={`friends[${index}].name`} />
<Field name={`friends.${index}.age`} />
<button
type="button"
onClick={() => arrayHelpers.remove(index)}
>
-
</button>
</div>
))}
<button
type="button"
onClick={() => arrayHelpers.push({ name: "", age: "" })}
>
+
</button>
</div>
)}
/>
<pre>{JSON.stringify(values, null, 2)}</pre>
</Form>
)}
/>
</div>
);
export default FriendList;
最佳答案
你的初始值错误,应该是这样的:
[{ name: "Julia", age: "27" }]
相反,您传递了 2 个数组项
关于javascript - 用于嵌套字段的 Formik 字段数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58064786/