javascript - 如何在 Typescript/Formik 中使用 useRef?
我正在将一个 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 上得到一个错误,提示 对象可能是 '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
同样,在我自定义的 FieldInput 组件中,当我使用 ref={fieldRef} 时,我收到一个错误,内容如下:
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
答案#1
如果你查看当前 forwardRef 方法的通用类型,第一个参数是 unknown。只需将输入的方法签名更改为
export const FieldInput = React.forwardRef<Input, FieldInputProps>(...)
TypeScript 将根据 forwardRef 方法的返回类型自动解析正确的类型。
