useFormik()

useFormik() 是一个自定义 React 钩子,它将直接返回所有 Formik 状态和助手。尽管有它的名字,但它并不适用于大多数用例。在内部,Formik 使用 useFormik 创建 <Formik> 组件(渲染 反应上下文 Provider)。如果你尝试通过上下文访问 Formik 状态,请使用 useFormikContext。仅当你不使用 <Formik>withFormik 时才使用此钩子。

¥useFormik() is a custom React hook that will return all Formik state and helpers directly. Despite its name, it is not meant for the majority of use cases. Internally, Formik uses useFormik to create the <Formik> component (which renders a React Context Provider). If you are trying to access Formik state via context, use useFormikContext. Only use this hook if you are NOT using <Formik> or withFormik.

** 请注意,<Field><FastField><ErrorMessage>connect()<FieldArray> 不能与 useFormik() 一起使用,因为它们都需要 React Context。

¥** Be aware that <Field>, <FastField>, <ErrorMessage>, connect(), and <FieldArray> will NOT work with useFormik() as they all require React Context.

useFormik() 的用例

¥Use cases for useFormik()

  • 你是贾里德

    ¥You are Jared

  • 你正在修改返回值并创建 <Formik> 的修改版本以供你自己使用

    ¥You are modifying the returned value and creating a modified version of <Formik> for your own consumption

  • 你想避免使用 React Context (可能是出于性能原因)

    ¥You want to avoid using React Context (possibly for perf reasons)

示例

¥Example

import React from 'react';
import { useFormik } from 'formik';
const SignupForm = () => {
const formik = useFormik({
initialValues: {
firstName: '',
lastName: '',
email: '',
},
onSubmit: values => {
alert(JSON.stringify(values, null, 2));
},
});
return (
<form onSubmit={formik.handleSubmit}>
<label htmlFor="firstName">First Name</label>
<input
id="firstName"
name="firstName"
type="text"
onChange={formik.handleChange}
value={formik.values.firstName}
/>
<label htmlFor="lastName">Last Name</label>
<input
id="lastName"
name="lastName"
type="text"
onChange={formik.handleChange}
value={formik.values.lastName}
/>
<label htmlFor="email">Email Address</label>
<input
id="email"
name="email"
type="email"
onChange={formik.handleChange}
value={formik.values.email}
/>
<button type="submit">Submit</button>
</form>
);
};

参考

¥Reference

useFormik<Values>(config: FormikConfig<Values>): FormikProps<Values>

一个返回 Formik 状态和辅助程序的自定义 React Hook。它在内部用于创建 <Formik> 组件,但为高级用例或不想使用 React Context 的人导出。

¥A custom React Hook that returns Formik states and helpers. It is used internally to create the <Formik> component, but is exported for advanced use cases or for those people that do not want to use React Context.

Formik 中文网 - 粤ICP备13048890号