簡體   English   中英

將 Formik 與 React.FC 一起使用

[英]Use Formik with React.FC

我有一個表單,它在 React 中設置為 function 組件,其中 forms 值由 state 掛鈎管理。 我想將 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 進行表單管理?

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沒有辦法知道這一點。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM