【问题标题】:How to use useRef with Typescript/Formik?如何将 useRef 与 Typescript/Formik 一起使用?
【发布时间】:2020-12-21 16:39:01
【问题描述】:

我将 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();
  };

我在 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

【问题讨论】:

    标签: javascript reactjs typescript react-native formik


    【解决方案1】:

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

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

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

    【讨论】:

    • 是的,我已经修复了它:snack.expo.io/HI9bdGAxf,但我必须使用any 而不是Input这里const fieldRef = useRef&lt;any&gt;(null);否则它会在fieldRef.current?.blur 上给出内联错误。有解决办法吗?
    • @Jnl 只需使用 const fieldRef = useRef(null); (TextInput 是从 'react-native' 导入的)
    猜你喜欢
    • 2020-11-17
    • 1970-01-01
    • 2020-08-31
    • 2021-04-14
    • 1970-01-01
    • 1970-01-01
    • 2021-03-01
    • 2020-11-19
    • 2020-04-16
    相关资源
    最近更新 更多