如何将 useRef 与 Typescript/Formik 一起使用?

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)

我该如何解决这些问题?

这是一个codesandbox:

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

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

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

Typescript 将根据 forwardRef 方法 return 类型自动解析正确的类型。