首页 > 解决方案 > 将 Formik 与 React.FC 一起使用

问题描述

我有一个表单,它在 React 中设置为函数组件,其中表单值由状态挂钩管理。我想将 Formik 添加到此,但是当我设置增强表单时,我收到此错误:

Argument of Type FC<Props> is not assignable to parameter of type 'CompositeComponent<FormikSharedConfig & FormikState<{}> & FormikActions<{}> & FormikHandlers & FormikComputedProps<{}> & FormikRegistration>

该组件的设置类似于

const Form: React.FC<Props> = () => {
    [formVal, setFormVal] = React.useState<string>('')
    [formValTwo, setFormValTwo] = React.useState<string>('')

    // some functions related to managing the form
    return (
       <>
         // render form
       </>
    )
}

const EnhancedForm = withFormik ({
    mapPropsToValues: () => ({...props})

    handleSubmit:(values, {setSubmitting}) => {...}

})(EnhancedForm) // above error shows here

我用错了Formik吗?如果是这样,我将如何为 React.FC 进行表单管理?

标签: reactjstypescriptformik

解决方案


的价值是Props多少?

在您的代码片段中,您为什么要这样做:

const EnhancedForm = withFormik ({
    mapPropsToValues: () => ({...props})

    handleSubmit:(values, {setSubmitting}) => {...}

})(EnhancedForm) // above error shows here

代替:

const EnhancedForm = withFormik ({
    mapPropsToValues: () => ({...props})

    handleSubmit:(values, {setSubmitting}) => {...}

})(Form) // above error shows here

也许你可以试试这个:

import { InjectedFormikProps } from 'formik';

interface FormValues {
  // The values of your form
  // email: string;
  // password: string;
}

interface Props {
  // your props
}

const Form: React.FC<InjectedFormikProps<Props, FormValues>> = () => {
    [formVal, setFormVal] = React.useState<string>('')
    [formValTwo, setFormValTwo] = React.useState<string>('')

    // some functions related to managing the form
    return (
       <>
         // render form
       </>
    )
}

const EnhancedForm = withFormik ({
    mapPropsToValues: () => ({...props})

    handleSubmit:(values, {setSubmitting}) => {...}

})(Form) // above error shows here

这样你就可以告诉 Typescript 你的Form组件接受 Formik 相关的 props。因为 Typescript 无法知道这一点。


推荐阅读