问题描述
我正在将ref
属性传递到我的自定义FieldInput中,该属性用于表单的Formik验证.但是,它给出了一些Typescript错误.例如,在我的函数中:
I am passing a ref
property into my custom FieldInput that I use for Formik validation of my form. However, it gives a few Typescript errors. 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();
};
我在Object is possibly 'undefined'.
的fieldRef.current上收到错误.我以为添加if条件可以解决此问题,但事实并非如此.另外,当我提交表格时,我会收到警告
I get an error on fieldRef.current that Object is possibly 'undefined'.
. I thought adding the if condition would fix it but it didn't. 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
类似地,在使用 ref={fieldRef}
的自定义FieldInput组件中,出现以下错误:
Similarly, in my custom FieldInput component where I use ref={fieldRef}
, I get an error that:
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
推荐答案
如果查看forwardRef
方法的当前泛型类型,则第一个参数是unknown
.只需将您的签名输入方法更改为
If you look into current generic types of your forwardRef
method, first parameter is unknown
. Just change your signature method of input to
export const FieldInput = React.forwardRef<Input, FieldInputProps>(...)
Typescript将根据forwardRef
方法返回类型自动解析正确的类型.
Typescript will automatically resolve correct type based on forwardRef
method return type.
这篇关于如何将useRef与Typescript/Formik一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!