connect()
是一个高阶组件 (HoC),允许你将任何内容挂接到 Formik 的上下文中。它在内部用于构造 <Field>
和 <Form>
,但你可以根据需求的变化使用它来构建新组件。
¥connect()
is a higher-order component (HoC) that allows you to hook anything into Formik's context. It is used internally to construct <Field>
and <Form>
, but you can use it to build out new components as your needs change.
¥Type signature
connect<OuterProps, Values = any>(Comp: React.ComponentType<OuterProps & { formik: FormikContext<Values> }>) => React.ComponentType<OuterProps>
¥Example
import React from 'react';import { connect, getIn } from 'formik';// This component renders an error message if a field has// an error and it's already been touched.const ErrorMessage = props => {// All FormikProps available on props.formik!const error = getIn(props.formik.errors, props.name);const touch = getIn(props.formik.touched, props.name);return touch && error ? error : null;};export default connect(ErrorMessage);