簡體   English   中英

如何在 Typescript/Formik 中使用 useRef?

[英]How to use useRef with Typescript/Formik?

我將一個ref屬性傳遞到我用於 Formik 表單驗證的自定義 FieldInput 中。 但是,它給出了一些 Typescript 錯誤。 例如,在我的函數中:

    const handleSubmitForm = (
    values: FormValues,
    helpers: FormikHelpers<FormValues>,
  ) => {

    setShowFlatList(true);
    Keyboard.dismiss();
    helpers.resetForm();
    if (fieldRef && fieldRef.current){
          fieldRef.current.blur();}
    helpers.resetForm();
  };

我在 fieldRef.current 上收到一個錯誤, Object is possibly 'undefined'. . 我認為添加 if 條件會解決它,但它沒有。 另外,當我提交表單時,我收到一條警告

Warning: An unhandled error was caught from submitForm()
Error: "fieldRef.current.blur is not a function. (In 'fieldRef.current.blur()', 'fieldRef.current.blur' is undefined)" in handleSubmitForm 

同樣,在我使用ref={fieldRef}自定義 FieldInput 組件中,我收到一個錯誤:

Type '{ ref: MutableRefObject<undefined>; setFieldTouched: (field: string, isTouched?: boolean | undefined, shouldValidate?: boolean | undefined) => void; handleChange: { ...; }; ... 4 more ...; placeholderText: string; }' is not assignable to type 'IntrinsicAttributes & FieldInputProps & { children?: ReactNode; }'.
  Property 'ref' does not exist on type 'IntrinsicAttributes & FieldInputProps & { children?: ReactNode; }'.ts(2322)

我該如何解決這些問題?

這是一個代碼沙盒:

https://snack.expo.io/@nhammad/jealous-beef-jerky-fix

如果您查看forwardRef方法的當前泛型類型,則第一個參數是unknown 只需將您的簽名輸入方法更改為

export const FieldInput = React.forwardRef<Input, FieldInputProps>(...)

Typescript 將根據forwardRef方法返回類型自動解析正確的類型。

暫無
暫無

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

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