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);