我正在通过一个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
同样,在我使用的自定义 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)
我该如何解决这些问题?
这是一个代码和框:
https://snack.expo.io/@nhammad/jealous-beef-jerky-fix https://snack.expo.io/@nhammad/jealous-beef-jerky-fix