useFormikContext()

useFormikContext() 是一个自定义 React 钩子,它将通过 反应上下文 返回所有 Formik 状态和辅助程序。

¥useFormikContext() is a custom React hook that will return all Formik state and helpers via React Context.

示例

¥Example

下面是一个与 Stripe 的 2 因素验证表单类似的表单示例。一旦你输入 6 位数字,表单就会自动提交(即无需按 Enter 键)。

¥Here's an example of a form that works similarly to Stripe's 2-factor verification form. As soon as you type a 6 digit number, the form will automatically submit (i.e. no enter keypress is needed).

import React from 'react';
import { useFormikContext, Formik, Form, Field } from 'formik';
const AutoSubmitToken = () => {
// Grab values and submitForm from context
const { values, submitForm } = useFormikContext();
React.useEffect(() => {
// Submit the form imperatively as an effect as soon as form values.token are 6 digits long
if (values.token.length === 6) {
submitForm();
}
}, [values, submitForm]);
return null;
};
const TwoFactorVerificationForm = () => (
<div>
<h1>2-step Verification</h1>
<p>Please enter the 6 digit code sent to your device</p>
<Formik
initialValues={{ token: '' }}
validate={values => {
const errors = {};
if (values.token.length < 5) {
errors.token = 'Invalid code. Too short.';
}
return errors;
}}
onSubmit={(values, actions) => {
setTimeout(() => {
alert(JSON.stringify(values, null, 2));
actions.setSubmitting(false);
}, 1000);
}}
>
<Form>
<Field name="token" type="tel" />
<AutoSubmitToken />
</Form>
</Formik>
</div>
);

参考

¥Reference

useFormikContext(): FormikProps<Values>

一个自定义的 React Hook,通过 React Context 返回 Formik 状态和辅助程序。因此,只有当存在可以从中提取内容的父 Formik React Context 时,此钩子才会起作用。如果在没有父上下文(即 <Formik> 组件或 withFormik 高阶组件的后代)的情况下调用,你将在控制台中收到警告。

¥A custom React Hook that returns Formik states and helpers via React Context. Thus, this hook will only work if there is a parent Formik React Context from which it can pull from. If called without a parent context (i.e. a descendent of a <Formik> component or withFormik higher-order component), you will get a warning in your console.

Formik 中文网 - 粤ICP备13048890号