<Formik> 是一个帮助你构建表单的组件。它使用了 React Motion 和 React Router 等库所流行的渲染属性模式。
¥<Formik> is a component that helps you with building forms. It uses a render
props pattern made popular by libraries like React Motion and React Router.
¥Example
import React from 'react';import { Formik } from 'formik';const BasicExample = () => (<div><h1>My Form</h1><FormikinitialValues={{ name: 'jared' }}onSubmit={(values, actions) => {setTimeout(() => {alert(JSON.stringify(values, null, 2));actions.setSubmitting(false);}, 1000);}}>{props => (<form onSubmit={props.handleSubmit}><inputtype="text"onChange={props.handleChange}onBlur={props.handleBlur}value={props.values.name}name="name"/>{props.errors.name && <div id="feedback">{props.errors.name}</div>}<button type="submit">Submit</button></form>)}</Formik></div>);
¥Props
¥Reference
¥Props
¥Formik render methods and props
有 2 种方法可以使用 <Formik /> 渲染事物
¥There are 2 ways to render things with <Formik />
<Formik component>
<Formik children>
在 2.x 中已弃用<Formik render>
¥ Deprecated in 2.x<Formik render>
每个渲染方法都将传递相同的属性:
¥Each render methods will be passed the same props:
dirty: boolean如果值与初始值不完全相等,则返回 true,否则返回 false。dirty 是只读计算属性,不应直接更改。
¥Returns true if values are not deeply equal from initial values, false otherwise.
dirty is a readonly computed property and should not be mutated directly.
errors: { [field: string]: string }表单验证错误。应与 initialValues 中定义的表单 values 的形状匹配。如果你使用的是 validationSchema(你应该是),键和形状将与你的架构完全匹配。在内部,Formik 代表你转换原始 是的,验证错误。如果你使用的是 validate,那么该函数将确定 errors 对象的形状。
¥Form validation errors. Should match the shape of your form's values defined
in initialValues. If you are using validationSchema (which you should be),
keys and shape will match your schema exactly. Internally, Formik transforms raw
Yup validation errors
on your behalf. If you are using validate, then that function will determine
the errors objects shape.
handleBlur: (e: any) => voidonBlur 事件处理程序。当你需要跟踪输入是否为 touched 时很有用。这应该传递给 <input onBlur={handleBlur} ... />
¥onBlur event handler. Useful for when you need to track whether an input has
been touched or not. This should be passed to <input onBlur={handleBlur} ... />
handleChange: (e: React.ChangeEvent<any>) => void通用输入更改事件处理程序。这将更新 values[key],其中 key 是事件触发输入的 name 属性。如果 name 属性不存在,handleChange 将查找输入的 id 属性。注意:这里的 "input" 表示所有 HTML 输入。
¥General input change event handler. This will update the values[key] where
key is the event-emitting input's name attribute. If the name attribute is
not present, handleChange will look for an input's id attribute. Note:
"input" here means all HTML inputs.
handleReset: () => void重置处理程序。将表单重置为其初始状态。这应该传递给 <button onClick={handleReset}>...</button>
¥Reset handler. Will reset the form to its initial state. This should be passed
to <button onClick={handleReset}>...</button>
handleSubmit: (e: React.FormEvent<HTMLFormElement>) => void提交处理程序。这应该传递给 <form onSubmit={props.handleSubmit}>...</form>。要了解有关提交流程的更多信息,请参阅 表单提交。
¥Submit handler. This should be passed to <form onSubmit={props.handleSubmit}>...</form>. To learn more about the submission process, see Form Submission.
isSubmitting: boolean表单的提交状态。如果提交正在进行,则返回 true,否则返回 false。重要:一旦尝试提交,Formik 就会将其设置为 true。要了解有关提交流程的更多信息,请参阅 表单提交。
¥Submitting state of the form. Returns true if submission is in progress and false otherwise. IMPORTANT: Formik will set this to true as soon as submission is attempted. To learn more about the submission process, see Form Submission.
isValid: boolean如果没有 errors(即 errors 对象为空),则返回 true,否则返回 false。
¥Returns true if there are no errors (i.e. the errors object is empty) and false otherwise.
注意:
isInitialValid在 2.x 中已弃用。但是,为了向后兼容,如果指定了isInitialValid属性,如果没有errors,则isValid将返回true;如果处于 "pristine" 条件(即不是dirty),则返回isInitialValid的结果。¥Note:
isInitialValidwas deprecated in 2.x. However, for backwards compatibility, if theisInitialValidprop is specified,isValidwill returntrueif the there are noerrors, or the result ofisInitialValidof the form if it is in "pristine" condition (i.e. notdirty).
isValidating: boolean如果 Formik 在提交期间运行验证,则返回 true,否则直接调用 [validateForm] false。要了解有关 isValidating 在提交过程中发生的情况的更多信息,请参阅 表单提交。
¥Returns true if Formik is running validation during submission, or by calling [validateForm] directly false otherwise. To learn more about what happens with isValidating during the submission process, see Form Submission.
resetForm: (nextState?: Partial<FormikState<Values>>) => void必须重置表单。唯一(可选)参数 nextState 是一个对象,其中任何 FormikState 字段都是可选的:
¥Imperatively reset the form. The only (optional) argument, nextState, is an object on which any of these FormikState fields are optional:
interface FormikState<Values> {/** Form values */values: Values;/** map of field names to specific error for that field */errors: FormikErrors<Values>;/** map of field names to **whether** the field has been touched */touched: FormikTouched<Values>;/** whether the form is currently submitting */isSubmitting: boolean;/** whether the form is currently validating (prior to submission) */isValidating: boolean;/** Top level status state, in case you need it */status?: any;/** Number of times user tried to submit the form */submitCount: number;}
如果指定了 nextState,Formik 会将 nextState.values 设置为新的 "初始状态",并使用 nextState 的相关值来更新表单的 initialValues 以及 initialTouched、initialStatus、initialErrors。这对于在进行更改后更改表单的初始状态(即 "base")非常有用。
¥If nextState is specified, Formik will set nextState.values as the new "initial state" and use the related values of nextState to update the form's initialValues as well as initialTouched, initialStatus, initialErrors. This is useful for altering the initial state (i.e. "base") of the form after changes have been made.
// typescript usagefunction MyForm(props: MyFormProps) {// using TSX Generics here to set <Values> to <Blog>return (<Formik<Blog>initialValues={props.initVals}onSubmit={(values, actions) => {props.onSubmit(values).then(() => {actions.setSubmitting(false);actions.resetForm({values: {// the type of `values` inferred to be Blogtitle: '',image: '',body: '',},// you can also set the other form states here});});}}>// etc</Formik>);}
如果省略 nextState,则 Formik 会将状态重置为原始初始状态。后者对于在 componentDidUpdate 或 useEffect 内调用 resetForm 很有用。
¥If nextState is omitted, then Formik will reset state to the original initial state. The latter is useful for calling resetForm within componentDidUpdate or useEffect.
actions.resetForm();
setErrors: (fields: { [field: string]: string }) => void强制设置 errors。
¥Set errors imperatively.
setFieldError: (field: string, errorMsg: string) => void强制设置字段的错误信息。field 应与你要更新的 errors 的密钥匹配。对于创建自定义输入错误处理程序很有用。
¥Set the error message of a field imperatively. field should match the key of
errors you wish to update. Useful for creating custom input error handlers.
setFieldTouched: (field: string, isTouched?: boolean, shouldValidate?: boolean) => Promise<void | FormikErrors>强制设置字段的触摸状态。field 应与你要更新的 touched 的密钥匹配。对于创建自定义输入模糊处理程序很有用。如果 validateOnBlur 设置为 true(默认情况下),调用此方法将触发验证运行。如果未指定,isTouched 默认为 true。你还可以通过传递第三个参数作为 false 来显式阻止/跳过验证。
¥Set the touched state of a field imperatively. field should match the key of
touched you wish to update. Useful for creating custom input blur handlers. Calling this method will trigger validation to run if validateOnBlur is set to true (which it is by default). isTouched defaults to true if not specified. You can also explicitly prevent/skip validation by passing a third argument as false.
如果 validateOnBlur 设置为 true 并且存在错误,这些错误将在返回的 Promise 中得到解决。
¥If validateOnBlur is set to true and there are errors, they will be resolved in the returned Promise.
submitForm: () => Promise触发表单提交。如果表单无效,promise 将被拒绝。
¥Trigger a form submission. The promise will be rejected if form is invalid.
submitCount: number用户尝试提交表单的次数。调用 handleSubmit 时增加,调用 handleReset 后重置。submitCount 是只读计算属性,不应直接改变。
¥Number of times user tried to submit the form. Increases when handleSubmit is called, resets after calling
handleReset. submitCount is readonly computed property and should not be mutated directly.
setFieldValue: (field: string, value: React.SetStateAction<any>, shouldValidate?: boolean) => Promise<void | FormikErrors>强制设置字段的值。field 应与你要更新的 values 的密钥匹配。对于创建自定义输入更改处理程序很有用。如果 validateOnChange 设置为 true(默认情况下),调用此函数将触发验证运行。你还可以通过传递第三个参数作为 false 来显式阻止/跳过验证。
¥Set the value of a field imperatively. field should match the key of
values you wish to update. Useful for creating custom input change handlers. Calling this will trigger validation to run if validateOnChange is set to true (which it is by default). You can also explicitly prevent/skip validation by passing a third argument as false.
如果 validateOnChange 设置为 true 并且存在错误,这些错误将在返回的 Promise 中得到解决。
¥If validateOnChange is set to true and there are errors, they will be resolved in the returned Promise.
setStatus: (status?: any) => void将顶层 status 设置为你想要的任何内容。对于控制与表单相关的任意顶层状态很有用。例如,你可以使用它将 API 响应传递回 handleSubmit 中的组件。
¥Set a top-level status to anything you want imperatively. Useful for
controlling arbitrary top-level state related to your form. For example, you can
use it to pass API responses back into your component in handleSubmit.
setSubmitting: (isSubmitting: boolean) => void强制设置 isSubmitting。你可以在 onSubmit 处理程序中使用 setSubmitting(false) 调用它来完成循环。要了解有关提交流程的更多信息,请参阅 表单提交。
¥Set isSubmitting imperatively. You would call it with setSubmitting(false) in your onSubmit handler to finish the cycle. To learn more about the submission process, see Form Submission.
setTouched: (fields: { [field: string]: boolean }, shouldValidate?: boolean) => Promise<void | FormikErrors>强制设置 touched。如果 validateOnBlur 设置为 true(默认情况下),调用此函数将触发验证运行。你还可以通过传递第二个参数作为 false 来显式阻止/跳过验证。
¥Set touched imperatively. Calling this will trigger validation to run if validateOnBlur is set to true (which it is by default). You can also explicitly prevent/skip validation by passing a second argument as false.
如果 validateOnBlur 设置为 true 并且存在错误,这些错误将在返回的 Promise 中得到解决。
¥If validateOnBlur is set to true and there are errors, they will be resolved in the returned Promise.
setValues: (fields: React.SetStateAction<{ [field: string]: any }>, shouldValidate?: boolean) => Promise<void | FormikErrors<Values>>强制设置 values。如果 validateOnChange 设置为 true(默认情况下),调用此函数将触发验证运行。你还可以通过传递第二个参数作为 false 来显式阻止/跳过验证。
¥Set values imperatively. Calling this will trigger validation to run if validateOnChange is set to true (which it is by default). You can also explicitly prevent/skip validation by passing a second argument as false.
如果 validateOnChange 设置为 true 并且存在错误,这些错误将在返回的 Promise 中得到解决。
¥If validateOnChange is set to true and there are errors, they will be resolved in the returned Promise.
status?: any一个顶层状态对象,可用于表示无法用其他方法表达/存储的表单状态。这对于捕获 API 响应并将其传递到内部组件非常有用。
¥A top-level status object that you can use to represent form state that can't otherwise be expressed/stored with other methods. This is useful for capturing and passing through API responses to your inner component.
status 只能通过调用 setStatus 来修改。
¥status should only be modified by calling
setStatus.
touched: { [field: string]: boolean }触及田野。每个键对应于已被触摸/访问的字段。
¥Touched fields. Each key corresponds to a field that has been touched/visited.
values: { [field: string]: any }你的表单的值。将具有 mapPropsToValues (如果指定)的结果或所有不是传递给封装组件的函数的 props 的形状。
¥Your form's values. Will have the shape of the result of mapPropsToValues
(if specified) or all props that are not functions passed to your wrapped
component.
validateForm: (values?: any) => Promise<FormikErrors<Values>>根据指定内容,强制调用 validate 或 validateSchema。你可以选择传递值进行验证,并相应地修改 Formik 状态,否则将使用表单的当前 values。
¥Imperatively call your validate or validateSchema depending on what was specified. You can optionally pass values to validate against and this modify Formik state accordingly, otherwise this will use the current values of the form.
validateField: (field: string) => void如果为给定字段指定,则强制调用字段的 validate 函数,或者使用 是的,schema.validateAt 和提供的顶层 validationSchema 属性运行模式验证。Formik 将使用当前字段值。
¥Imperatively call field's validate function if specified for given field or run schema validation using Yup's schema.validateAt and the provided top-level validationSchema prop. Formik will use the current field value.
component?: React.ComponentType<FormikProps<Values>><Formik component={ContactForm} />;const ContactForm = ({handleSubmit,handleChange,handleBlur,values,errors,}) => (<form onSubmit={handleSubmit}><inputtype="text"onChange={handleChange}onBlur={handleBlur}value={values.name}name="name"/>{errors.name && <div>{errors.name}</div>}<button type="submit">Submit</button></form>);
警告:<Formik component> 优先于 <Formik render>,因此请勿在同一个 <Formik> 中同时使用两者。
¥Warning: <Formik component> takes precedence over <Formik render> so
don’t use both in the same <Formik>.
render: (props: FormikProps<Values>) => ReactNode在 2.x 中已弃用
¥Deprecated in 2.x
<Formik render={props => <ContactForm {...props} />} /><Formikrender={({ handleSubmit, handleChange, handleBlur, values, errors }) => (<form onSubmit={handleSubmit}><inputtype="text"onChange={handleChange}onBlur={handleBlur}value={values.name}name="name"/>{errors.name &&<div>{errors.name}</div>}<button type="submit">Submit</button></form>)}/>
children?: React.ReactNode | (props: FormikProps<Values>) => ReactNode<Formik children={props => <ContactForm {...props} />} />// or...<Formik>{({ handleSubmit, handleChange, handleBlur, values, errors }) => (<form onSubmit={handleSubmit}><inputtype="text"onChange={handleChange}onBlur={handleBlur}value={values.name}name="name"/>{errors.name &&<div>{errors.name}</div>}<button type="submit">Submit</button></form>)}</Formik>
enableReinitialize?: boolean默认为 false。控制 Formik 是否应在 initialValues 更改时重置表单(使用深度相等)。
¥Default is false. Control whether Formik should reset the form if
initialValues changes (using deep equality).
isInitialValid?: boolean2.x 中已弃用,请使用 initialErrors 代替
¥Deprecated in 2.x, use initialErrors 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.
initialErrors?: FormikErrors<Values>表单的初始字段错误,Formik 会将这些值作为 errors 提供给渲染方法组件。
¥Initial field errors of the form, Formik will make these values available to
render methods component as errors.
注意:initialErrors 对于高阶组件 withFormik 不可用,请使用 mapPropsToErrors 代替。
¥Note: initialErrors is not available to the higher-order component withFormik, use
mapPropsToErrors instead.
initialStatus?: any表单的初始 status 的任意值。如果重置表单,该值将被恢复。
¥An arbitrary value for the initial status of the form. If the form is reset, this value will be restored.
注意:initialStatus 对于高阶组件 withFormik 不可用,请使用 mapPropsToStatus 代替。
¥Note: initialStatus is not available to the higher-order component withFormik, use
mapPropsToStatus instead.
initialTouched?: FormikTouched<Values>初始访问表单的字段时,Formik 会将这些值作为 touched 提供给渲染方法组件。
¥Initial visited fields of the form, Formik will make these values available to
render methods component as touched.
注意:initialTouched 对于高阶组件 withFormik 不可用,请使用 mapPropsToTouched 代替。
¥Note: initialTouched is not available to the higher-order component withFormik, use
mapPropsToTouched instead.
initialValues: Values表单的初始字段值,Formik 会将这些值作为 values 提供给渲染方法组件。
¥Initial field values of the form, Formik will make these values available to
render methods component as values.
即使默认情况下你的表单为空,你也必须使用初始值初始化所有字段,否则 React 会抛出错误,表明你已将输入从不受控更改为受控。
¥Even if your form is empty by default, you must initialize all fields with initial values otherwise React will throw an error saying that you have changed an input from uncontrolled to controlled.
注意:initialValues 不适用于高阶组件,请使用 mapPropsToValues 代替。
¥Note: initialValues not available to the higher-order component, use
mapPropsToValues instead.
onReset?: (values: Values, formikBag: FormikBag) => void你的可选表单重置处理程序。你的表单 values 和 "FormikBag" 已通过。
¥Your optional form reset handler. It is passed your forms values and the
"FormikBag".
onSubmit: (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.
注意:errors、touched、status 和所有事件处理程序不包含在 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
onSubmitis async, then Formik will automatically setisSubmittingtofalseon your behalf once it has resolved. This means you do NOT need to callformikBag.setSubmitting(false)manually. However, if youronSubmitfunction is synchronous, then you need to callsetSubmitting(false)on your own.
validate?: (values: Values) => 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:
同步并返回一个 errors 对象。
¥Synchronous and return an errors object.
// Synchronous validationconst validate = values => {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 Validationconst sleep = ms => new Promise(resolve => setTimeout(resolve, ms));const validate = values => {return sleep(2000).then(() => {const errors = {};if (['admin', 'null', 'god'].includes(values.username)) {errors.username = 'Nice try';}// ...return errors;});};
validateOnBlur?: boolean默认为 true。使用此选项对 blur 事件运行验证。更具体地说,当调用 handleBlur、setFieldTouched 或 setTouched 时。
¥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 相关方法运行验证。更具体地说,当调用 handleChange、setFieldValue 或 setValues 时。
¥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 在 <Formik /> 组件安装和/或 initialValues 更改时运行验证。
¥Default is false. Use this option to tell Formik to run validations when the <Formik /> component mounts
and/or initialValues change.
validationSchema?: Schema | (() => 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.