简体   繁体   English

动态添加字段到 Formik 表单

[英]Dynamically add fields to Formik form

I need a way to add fields to a Formik form in a for loop.我需要一种在 for 循环中将字段添加到 Formik 表单的方法。 I've read the documentation for the FieldArray component, but I don't really understand how to use it.我已经阅读了 FieldArray 组件的文档,但我并不真正了解如何使用它。 This is my current code:这是我当前的代码:

function generate(values) {
        for (let i = 0; i < 10; i++) {
            values.test.push({
                hello: "world"
            })
        }
    }

    return (
        <div>
            <Formik initialValues={{test: []}}/>
            {(values)=>(
                <Form>
                    <FieldArray>
                        {()=>generate(values)}
                        <p>{JSON.stringify(values)}</p>
                    </FieldArray>
                </Form>
            )}
        </div>
    )

At the moment, it just shows an empty page.目前,它只显示一个空白页面。 Not even an error message.甚至没有错误消息。

The reason your code above is not working is because you are invoking the field array and form outside of <Formik />您上面的代码不起作用的原因是因为您正在<Formik />之外调用字段数组和表单

It should be:它应该是:

<Formik render={({ values }) => (
  <Form>
    <FieldArray />
  </Form>
)/>

And not:并不是:

<Formik initialValues={{test: []}} />
<Form>
  <FieldArray />
</Form>

You can see a clearer example here: https://codesandbox.io/s/1o8n593z6q你可以在这里看到一个更清晰的例子: https://codesandbox.io/s/1o8n593z6q

You can just use setValues to dynamically add or remove fields form formik.您可以只使用setValues动态添加或删除表单 formik 的字段。

Here's a code sample it might help这是一个可能有帮助的代码示例

      <Formik initialValues={{} as Record<string, any>} onSubmit={() => {}}>
    {({values, setValues}) => (
      <Form>
        {customers.map(e => (
          <Component
            name={e.firstName}
            customerId={e.customerId}
            onClick={() => {
              // @ts-ignore
              if (values?.[e.customerId])
                setValues(prev => _.omit(prev, e.customerId));
              else {
                setValues({...values, [e.customerId]: e});
              }
            }}
            // @ts-ignore
            isSelected={values?.[e.customerId]}
          />
        ))}

        {Object.values(values).map(v => (
          <h5 style={{color: 'red'}}>{v.firstName}</h5>
        ))}
      </Form>
    )}
  </Formik>

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

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