繁体   English   中英

嵌套字段的 Formik 字段数组

[英]Formik Field Array for Nested fields

我想在<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 个数组项

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM