如何将useRef与Typescript / Formik结合使用?

时间:2020-09-02 13:35:37

标签: javascript reactjs typescript react-native formik

我正在将ref属性传递到我的自定义FieldInput中,该属性用于表单的Formik验证。但是,它给出了一些Typescript错误。例如,在我的函数中:

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

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

我在Object is possibly 'undefined'.的fieldRef.current上收到错误。我以为添加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

1 个答案:

答案 0 :(得分:1)

如果您查看forwardRef方法的当前通用类型,则第一个参数为unknown。只需将您的签名输入方法更改为

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

Typescript将基于forwardRef方法返回类型自动解析正确的类型。