创建一个高阶 React 组件类,将 props 和表单处理程序(“FormikBag”)传递到从提供的选项派生的组件中。

¥Create a higher-order React component class that passes props and form handlers (the "FormikBag") into your component derived from supplied options.



import React from 'react';
import { withFormik } from 'formik';
const MyForm = props => {
const {
} = props;
return (
<form onSubmit={handleSubmit}>
{errors.name && touched.name && <div id="feedback">{errors.name}</div>}
<button type="submit">Submit</button>
const MyEnhancedForm = withFormik({
mapPropsToValues: () => ({ name: '' }),
// Custom sync validation
validate: values => {
const errors = {};
if (!values.name) {
errors.name = 'Required';
return errors;
handleSubmit: (values, { setSubmitting }) => {
setTimeout(() => {
alert(JSON.stringify(values, null, 2));
}, 1000);
displayName: 'BasicForm',





displayName?: string

当你的内部表单组件是无状态功能组件时,你可以使用 displayName 选项为该组件指定一个适当的名称,以便你可以更轻松地在 React 开发工具 中找到它。如果指定,你的封装表单将显示为 Formik(displayName)。如果省略,它将显示为 Formik(Component)。类组件(例如 class XXXXX extends React.Component {..})不需要此选项。

¥When your inner form component is a stateless functional component, you can use the displayName option to give the component a proper name so you can more easily find it in React DevTools. If specified, your wrapped form will show up as Formik(displayName). If omitted, it will show up as Formik(Component). This option is not required for class components (e.g. class XXXXX extends React.Component {..}).

enableReinitialize?: boolean

默认为 false。控制如果封装的组件 props 发生变化,Formik 是否应该重置表单(使用深度相等)。

¥Default is false. Control whether Formik should reset the form if the wrapped component props change (using deep equality).

handleSubmit: (values: Values, formikBag: FormikBag) => void | Promise<any>

你的表单提交处理程序。它传递给你的表单 values 和 "FormikBag",其中包括一个包含 注入的属性和方法 子集的对象(即名称以 set<Thing> + resetForm 开头的所有方法)以及传递给封装组件的任何 props。

¥Your form submission handler. It is passed your forms values and the "FormikBag", which includes an object containing a subset of the injected props and methods (i.e. all the methods with names that start with set<Thing> + resetForm) and any props that were passed to the wrapped component.

"FormikBag" 号

¥The "FormikBag"

  • props(传递给封装组件的属性)

    ¥props (props passed to the wrapped component)

  • resetForm

  • setErrors

  • setFieldError

  • setFieldTouched

  • setFieldValue

  • setStatus

  • setSubmitting

  • setTouched

  • setValues

注意:errorstouchedstatus 和所有事件处理程序不包含在 FormikBag 中。

¥Note: errors, touched, status and all event handlers are NOT included in the FormikBag.

重要:如果 onSubmit 是异步的,那么一旦解决,Formik 将自动代表你将 isSubmitting 设置为 false。这意味着你不需要手动调用 formikBag.setSubmitting(false)。但是,如果你的 onSubmit 函数是同步的,那么你需要自己调用 setSubmitting(false)

¥IMPORTANT: If onSubmit is async, then Formik will automatically set isSubmitting to false on your behalf once it has resolved. This means you do NOT need to call formikBag.setSubmitting(false) manually. However, if your onSubmit function is synchronous, then you need to call setSubmitting(false) on your own.

isInitialValid?: boolean | (props: Props) => boolean

2.x 中已弃用,请使用 mapPropsToErrors 代替

¥Deprecated in 2.x, use mapPropsToErrors instead

挂载前控制 isValid prop 的初始值。你还可以传递一个函数。当你想要在初始安装时启用/禁用提交和重置按钮的情况下非常有用。

¥Control the initial value of isValid prop prior to mount. You can also pass a function. Useful for situations when you want to enable/disable a submit and reset buttons on initial mount.

mapPropsToErrors?: (props: Props) => FormikErrors<Values>

如果指定了此选项,则 Formik 会将其结果传输到可更新的表单状态,并使这些值最初作为 props.errors 可用于新组件。对于将任意错误状态实例化到表单中非常有用。提醒一下,验证运行后,props.errors 将被覆盖。如果表单被重置,Formik 也会将 props.errors 重置为此初始值(并且此函数将重新运行)。

¥If this option is specified, then Formik will transfer its results into updatable form state and make these values available to the new component as props.errors initially. Useful for instantiating arbitrary error state into your form. As a reminder, props.errors will be overwritten as soon as validation runs. Formik will also reset props.errors to this initial value (and this function will be re-run) if the form is reset.

mapPropsToStatus?: (props: Props) => any

如果指定了此选项,那么 Formik 会将其结果传输到可更新的表单状态,并使这些值作为 props.status 可用于新组件。对于将任意状态存储或实例化到表单中非常有用。提醒一下,如果重置表单,status 将重置为该初始值(并且该函数将重新运行)。

¥If this option is specified, then Formik will transfer its results into updatable form state and make these values available to the new component as props.status. Useful for storing or instantiating arbitrary state into your form. As a reminder, status will be reset to this initial value (and this function will be re-run) if the form is reset.

mapPropsToTouched?: (props: Props) => FormikTouched<Values>

如果指定了此选项,那么 Formik 会将其结果传输到可更新的表单状态,并使这些值作为 props.touched 可用于新组件。对于在表单中实例化任意触摸状态(即将字段标记为已访问)非常有用。提醒一下,如果重置表单,Formik 将使用此初始值(并且此函数将重新运行)。

¥If this option is specified, then Formik will transfer its results into updatable form state and make these values available to the new component as props.touched. Useful for instantiating arbitrary touched state (i.e. marking fields as visited) into your form. As a reminder, Formik will use this initial value (and this function will be re-run) if the form is reset.

mapPropsToValues?: (props: Props) => Values

如果指定了此选项,那么 Formik 会将其结果传输到可更新的表单状态,并使这些值作为 props.values 可用于新组件。如果未指定 mapPropsToValues,则 Formik 会将所有非函数的 props 映射到内部组件的 props.values。也就是说,如果省略它,Formik 将只传递 props,其中 typeof props[k] !== 'function',其中 k 是某个关键。

¥If this option is specified, then Formik will transfer its results into updatable form state and make these values available to the new component as props.values. If mapPropsToValues is not specified, then Formik will map all props that are not functions to the inner component's props.values. That is, if you omit it, Formik will only pass props where typeof props[k] !== 'function', where k is some key.

即使你的表单没有从其父表单接收任何 props,也可以使用 mapPropsToValues 来初始化表单空状态。

¥Even if your form is not receiving any props from its parent, use mapPropsToValues to initialize your forms empty state.

validate?: (values: Values, props: Props) => FormikErrors<Values> | Promise<any>

注意:我建议使用 validationSchema 和 Yup 进行验证。然而,validate 是一种无依赖、简单的方式来验证你的表单。

¥Note: I suggest using validationSchema and Yup for validation. However, validate is a dependency-free, straightforward way to validate your forms.

使用函数验证表单的 values。该函数可以是:

¥Validate the form's values with function. This function can either be:

  1. 同步并返回一个 errors 对象。

    ¥Synchronous and return an errors object.

// Synchronous validation
const validate = (values, props) => {
const errors = {};
if (!values.email) {
errors.email = 'Required';
} else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(values.email)) {
errors.email = 'Invalid email address';
return errors;
  • 异步并返回一个 Promise,该 Promise 解析为包含 errors 的对象

    ¥Asynchronous and return a Promise that's resolves to an object containing errors

// Async Validation
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
const validate = (values, props) => {
return sleep(2000).then(() => {
const errors = {};
if (['admin', 'null', 'god'].includes(values.username)) {
errors.username = 'Nice try';
// ...
return errors;

validateOnBlur?: boolean

默认为 true。使用此选项对 blur 事件运行验证。更具体地说,当调用 handleBlursetFieldTouchedsetTouched 时。

¥Default is true. Use this option to run validations on blur events. More specifically, when either handleBlur, setFieldTouched, or setTouched are called.

validateOnChange?: boolean

默认为 true。使用此选项告诉 Formik 对 change 事件和 change 相关方法运行验证。更具体地说,当调用 handleChangesetFieldValuesetValues 时。

¥Default is true. Use this option to tell Formik to run validations on change events and change-related methods. More specifically, when either handleChange, setFieldValue, or setValues are called.

validateOnMount?: boolean

默认为 false。使用此选项告诉 Formik 在安装封装组件和/或 initialValues 更改时运行验证(以低优先级)。

¥Default is false. Use this option to tell Formik to run validation (at low priority) when the wrapped component mounts and/or initialValues change.

validationSchema?: Schema | ((props: Props) => Schema)

是的模式 或返回 Yup 模式的函数。这用于验证。错误通过键映射到内部组件的 errors。它的键应该与 values 的键匹配。

¥A Yup schema or a function that returns a Yup schema. This is used for validation. Errors are mapped by key to the inner component's errors. Its keys should match those of values.


¥Injected props and methods

这些与 <Formik render={props => ...} /> 的属性相同

¥These are identical to the props of <Formik render={props => ...} />

Formik 中文网 - 粤ICP备13048890号