javascript - ¿Cómo usar useRef con Typescript/Formik?
Estoy pasando una propiedad ref a mi FieldInput personalizado que uso para la validación de Formik de mi formulario. Sin embargo, da algunos errores de Typescript. Por ejemplo, en mi función:
const handleSubmitForm = (
values: FormValues,
helpers: FormikHelpers<FormValues>,
) => {
setShowFlatList(true);
Keyboard.dismiss();
helpers.resetForm();
if (fieldRef && fieldRef.current){
fieldRef.current.blur();}
helpers.resetForm();
};
Obtengo un error en fieldRef.current que El objeto posiblemente es 'undefined'.. Pensé que agregar la condición if lo solucionaría, pero no lo hizo. Además, cuando envío el formulario, recibo una advertencia de que
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
De manera similar, en mi componente personalizado FieldInput donde uso ref={fieldRef}, obtengo un error que:
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)
¿Cómo puedo arreglar estos?
Aquí hay un codesandbox:
https://snack.expo.io/@nhammad/jealous-beef-jerky-fix
Respuesta #1
Si miras los tipos genéricos actuales de tu método forwardRef, el primer parámetro es unknown. Simplemente cambia la firma de tu método de entrada a
export const FieldInput = React.forwardRef<Input, FieldInputProps>(...)
Typescript resolverá automáticamente el tipo correcto basado en el tipo de retorno del método forwardRef.
