connect()
是一个高阶组件 (HoC),它允许你将任何东西连接到 Formik 的上下文。它在内部用于构建 <Field>
和 <Form>
,但你也可以用它来构建新的组件以满足你的需求。
connect<OuterProps, Values = any>(Comp: React.ComponentType<OuterProps & { formik: FormikContext<Values> }>) => React.ComponentType<OuterProps>
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);