数组和嵌套对象

Formik 开箱即用地支持嵌套对象和数组。这些主题有些相关,因为它们都利用相同的语法。

¥Formik has support for nested objects and arrays out of the box. These subjects are somewhat related because they both leverage the same syntax.

嵌套对象

¥Nested Objects

Formik 中的 name 属性可以使用类似 lodash 的点路径来引用嵌套的 Formik 值。这意味着你不再需要展平表单的值。

¥The name props in Formik can use lodash-like dot paths to reference nested Formik values. This means that you do not need to flatten out your form's values anymore.

import React from 'react';
import { Formik, Form, Field } from 'formik';
export const NestedExample = () => (
<div>
<h1>Social Profiles</h1>
<Formik
initialValues={{
social: {
facebook: '',
twitter: '',
},
}}
onSubmit={values => {
// same shape as initial values
console.log(values);
}}
>
<Form>
<Field name="social.facebook" />
<Field name="social.twitter" />
<button type="submit">Submit</button>
</Form>
</Formik>
</div>
);

数组

¥Arrays

Formik 还支持开箱即用的数组和对象数组。对 name 字符串使用类似于 lodash 的括号语法,你可以快速为列表中的项目构建字段。

¥Formik also has support for arrays and arrays of objects out of the box. Using lodash-like bracket syntax for name string you can quickly build fields for items in a list.

import React from 'react';
import { Formik, Form, Field } from 'formik';
export const BasicArrayExample = () => (
<div>
<h1>Friends</h1>
<Formik
initialValues={{
friends: ['jared', 'ian'],
}}
onSubmit={values => {
// same shape as initial values
console.log(values);
}}
>
<Form>
<Field name="friends[0]" />
<Field name="friends[1]" />
<button type="submit">Submit</button>
</Form>
</Formik>
</div>
);

有关操作(添加/删除等)列表中的项目的更多信息,请参阅 <FieldArray> 组件上的 API 参考部分。

¥For more information around manipulating (add/remove/etc) items in lists, see the API reference section on the <FieldArray> component.

避免嵌套

¥Avoid nesting

如果你想避免这种默认行为,Formik 还支持包含带点的字段。

¥If you want to avoid this default behavior Formik also has support for it to have fields with dots.

import React from 'react';
import { Formik, Form, Field } from 'formik';
export const NestedExample = () => (
<div>
<h1>Social Profiles</h1>
<Formik
initialValues={{
'owner.fullname': '',
}}
onSubmit={values => {
// same shape as initial values
console.log(values);
}}
>
<Form>
<Field name="['owner.fullname']" />
<button type="submit">Submit</button>
</Form>
</Formik>
</div>
);
Formik 中文网 - 粤ICP备13048890号