简体   繁体   English

如何在 Typescript/Formik 中使用 useRef?

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

I am passing a ref property into my custom FieldInput that I use for Formik validation of my form.我将一个ref属性传递到我用于 Formik 表单验证的自定义 FieldInput 中。 However, it gives a few Typescript errors.但是,它给出了一些 Typescript 错误。 For instance, in my function:例如,在我的函数中:

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

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

I get an error on fieldRef.current that Object is possibly 'undefined'.我在 fieldRef.current 上收到一个错误, Object is possibly 'undefined'. . . I thought adding the if condition would fix it but it didn't.我认为添加 if 条件会解决它,但它没有。 Also, when I submit the form, I get a warning that另外,当我提交表单时,我收到一条警告

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 

Similarly, in my custom FieldInput component where I use ref={fieldRef} , I get an error that:同样,在我使用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)

How can I fix these?我该如何解决这些问题?

Here's a codesandbox:这是一个代码沙盒:

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

If you look into current generic types of your forwardRef method, first parameter is unknown .如果您查看forwardRef方法的当前泛型类型,则第一个参数是unknown Just change your signature method of input to只需将您的签名输入方法更改为

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

Typescript will automatically resolve correct type based on forwardRef method return type. Typescript 将根据forwardRef方法返回类型自动解析正确的类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM