<FieldArray />

<FieldArray /> 是一个组件,用于帮助处理常见的数组/列表操作。您可以向其传递一个 name 属性,该属性包含 values 中保存相关数组的键的路径。然后,<FieldArray /> 将通过渲染属性为您提供对数组辅助方法的访问权限。为了方便起见,调用这些方法将触发验证并为您管理 touched

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.
export const FriendList = () => (
<div>
<h1>Friend List</h1>
<Formik
initialValues={{ friends: ['jared', 'ian', 'brent'] }}
onSubmit={values =>
setTimeout(() => {
alert(JSON.stringify(values, null, 2));
}, 500)
}
render={({ values }) => (
<Form>
<FieldArray
name="friends"
render={arrayHelpers => (
<div>
{values.friends && values.friends.length > 0 ? (
values.friends.map((friend, index) => (
<div key={index}>
<Field name={`friends.${index}`} />
<button
type="button"
onClick={() => arrayHelpers.remove(index)} // remove a friend from the list
>
-
</button>
<button
type="button"
onClick={() => arrayHelpers.insert(index, '')} // insert an empty string at a position
>
+
</button>
</div>
))
) : (
<button type="button" onClick={() => arrayHelpers.push('')}>
{/* show this when user has removed all friends from the list */}
Add a friend
</button>
)}
<div>
<button type="submit">Submit</button>
</div>
</div>
)}
/>
</Form>
)}
/>
</div>
);

name: string

values 中相关键的名称或路径。

validateOnChange?: boolean

默认为 true。确定是否应该或不应该在任何数组操作之后运行表单验证。

FieldArray 对象数组

您还可以通过遵循 object[index].propertyobject.index.property 的约定来遍历对象数组,作为 <Field /><input /> 元素在 <FieldArray /> 中的 name 属性。

<Form>
<FieldArray
name="friends"
render={arrayHelpers => (
<div>
{values.friends.map((friend, index) => (
<div key={index}>
{/** both these conventions do the same */}
<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>
)}
/>
</Form>

FieldArray 验证注意事项

使用 <FieldArray> 进行验证可能很棘手。

如果您使用 validationSchema 并且您的表单具有数组验证要求(如最小长度)以及嵌套数组字段要求,则显示错误可能很棘手。Formik/Yup 将从内到外显示验证错误。例如,

const schema = Yup.object().shape({
friends: Yup.array()
.of(
Yup.object().shape({
name: Yup.string().min(4, 'too short').required('Required'), // these constraints take precedence
salary: Yup.string().min(3, 'cmon').required('Required'), // these constraints take precedence
})
)
.required('Must have friends') // these constraints are shown if and only if inner constraints are satisfied
.min(3, 'Minimum of 3 friends'),
});

由于 Yup 和您的自定义验证函数始终应将错误消息输出为字符串,因此在显示错误消息时,您需要嗅探嵌套错误是数组还是字符串。

所以……要显示 'Must have friends''Minimum of 3 friends'(我们示例中的数组验证约束)……

错误

// within a `FieldArray`'s render
const FriendArrayErrors = errors =>
errors.friends ? <div>{errors.friends}</div> : null; // app will crash

正确

// within a `FieldArray`'s render
const FriendArrayErrors = errors =>
typeof errors.friends === 'string' ? <div>{errors.friends}</div> : null;

对于嵌套字段错误,您应该假设除非您已检查过,否则对象中的任何部分均未定义。因此,您可能希望自己创建一个自定义的 <ErrorMessage /> 组件,如下所示

import { Field, getIn } from 'formik';
const ErrorMessage = ({ name }) => (
<Field
name={name}
render={({ form }) => {
const error = getIn(form.errors, name);
const touch = getIn(form.touched, name);
return touch && error ? error : null;
}}
/>
);
// Usage
<ErrorMessage name="friends[0].name" />; // => null, 'too short', or 'required'

注意:在 Formik v0.12 / 1.0 中,可能会向 FieldFieldArray 添加一个新的 meta 属性,该属性将为您提供相关的元数据,例如 errortouch,这将使您不必使用 Formik 或 lodash 的 getIn 或自己检查路径是否已定义。

FieldArray 辅助函数

以下方法可通过渲染属性获得。

  • push: (obj: any) => void:将值添加到数组的末尾
  • swap: (indexA: number, indexB: number) => void:交换数组中的两个值
  • move: (from: number, to: number) => void:将数组中的一个元素移动到另一个索引
  • insert: (index: number, value: any) => void:在给定索引处将元素插入数组
  • unshift: (value: any) => number:将元素添加到数组的开头并返回其长度
  • remove<T>(index: number): T | undefined:删除数组中指定索引处的元素并返回它
  • pop<T>(): T | undefined:删除并返回数组末尾的值
  • replace: (index: number, value: any) => void:替换数组中给定索引处的值

FieldArray 渲染方法

有三种方法可以使用 <FieldArray /> 渲染内容

  • <FieldArray name="..." component>
  • <FieldArray name="..." render>
  • <FieldArray name="..." children>

render: (arrayHelpers: ArrayHelpers) => React.ReactNode

import React from 'react';
import { Formik, Form, Field, FieldArray } from 'formik'
export const FriendList = () => (
<div>
<h1>Friend List</h1>
<Formik
initialValues={{ friends: ['jared', 'ian', 'brent'] }}
onSubmit={...}
render={formikProps => (
<FieldArray
name="friends"
render={({ move, swap, push, insert, unshift, pop }) => (
<Form>
{/*... use these however you want */}
</Form>
)}
/>
/>
</div>
);

component: React.ReactNode

import React from 'react';
import { Formik, Form, Field, FieldArray } from 'formik'
export const FriendList = () => (
<div>
<h1>Friend List</h1>
<Formik
initialValues={{ friends: ['jared', 'ian', 'brent'] }}
onSubmit={...}
render={formikProps => (
<FieldArray
name="friends"
component={MyDynamicForm}
/>
)}
/>
</div>
);
// In addition to the array helpers, Formik state and helpers
// (values, touched, setXXX, etc) are provided through a `form`
// prop
export const MyDynamicForm = ({
move, swap, push, insert, unshift, pop, form
}) => (
<Form>
{/** whatever you need to do */}
</Form>
);

children: func

import React from 'react';
import { Formik, Form, Field, FieldArray } from 'formik'
export const FriendList = () => (
<div>
<h1>Friend List</h1>
<Formik
initialValues={{ friends: ['jared', 'ian', 'brent'] }}
onSubmit={...}
render={formikProps => (
<FieldArray name="friends">
{({ move, swap, push, insert, unshift, pop, form }) => {
return (
<Form>
{/*... use these however you want */}
</Form>
);
}}
</FieldArray>
)}
/>
</div>
);
此页面是否有帮助?

订阅我们的时事通讯

最新的 Formik 新闻、文章和资源,发送到您的收件箱。

版权所有 © 2020 Formium, Inc. 保留所有权利。