Tengo un formulario con un campo y un botón, me gustaría que el botón se destaque en el desenfoque de la entrada, así que he colocado una referencia en un botón.
const btnRef = useRef<HTMLElement>(null);y función escrita
const passFocus = () => { btnRef.current?.focus(); };pero en el botón ref mecanografiado tiene un problema al decir
Type 'RefObject<HTMLElement>' is not assignable to type 'MutableRefObject<null>'. Types of property 'current' are incompatible. Type 'HTMLElement | null' is not assignable to type 'null'. Type 'HTMLElement' is not assignable to type 'null'.ts(2322) Button.tsx(10, 3): The expected type comes from property 'ref' which is declared here on type 'IntrinsicAttributes & Props & { children?: ReactNode; }'el botón en sí se ve así
<Button color={COLORS.TERTIARY} textColor={COLORS.FONT_COLOR} onPress={handleSubmit((data) => onSubmit(data))} ref={btnRef} > Enter </Button>Si esto tiene alguna importancia, esto es React Native
Es porque en el primer render ref es nulo y agrega solo HTMLElement para el tipo, por lo que debe hacer lo siguiente:
const btnRef = useRef<HTMLElement | null>(null); const passFocus = () => { btnRef?.current?.focus(); };y encadenamiento opcional para btnRef en passFocus