En un componente React, quiero mantener una referencia a un nodo secundario que puede diferir en tipo (div, img, etc.). Así que definí una variable miembro:
export class MyComp extends Component<IProperties, IState> { private triggerRef = React.createRef<HTMLElement>(); ... }y quiero usar eso para mantener la referencia requerida:
const trigger = <div ref={this.triggerRef} className={className} style={style} />;Sin embargo, esto produce un error:
Type 'RefObject<HTMLElement>' is not assignable to type 'string | ((instance: HTMLDivElement | null) => void) | RefObject<HTMLDivElement> | null | undefined'. Type 'RefObject<HTMLElement>' is not assignable to type 'RefObject<HTMLDivElement>'. Property 'align' is missing in type 'HTMLElement' but required in type 'HTMLDivElement'.ts(2322) lib.dom.d.ts(6708, 5): 'align' is declared here. index.d.ts(143, 9): The expected type comes from property 'ref' which is declared here on type 'DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>' El Type 'RefObject<HTMLElement>' is not assignable to type 'RefObject<HTMLDivElement>' dice que los dos tipos de objeto ref son incompatibles, aunque HTMLDivElement extiende HTMLElement . Espero que los tipos de referencia sean compatibles con la asignación, ya que claramente se superponen.
¿Cuál es el enfoque correcto aquí, sin cambiar la variable miembro para usar HTMLDivElement ?
Esta no es realmente una respuesta a mi pregunta original, sino una solución fácil y funciona muy bien:
const trigger = <div ref={this.triggerRef as React.RefObject<HTMLDivElement>} className={className} style={style} />Para todas las personas que vienen a este hilo porque se encuentran con este problema al escribir un enlace personalizado haciendo algo con un elemento DOM, lo siguiente funciona:
function useMyCustomHook<T extends HTMLElement>{ const myRef = useRef<T>(null) // do something with the ref, eg adding event listeners return {ref: myRef} } function MyComponent(){ const {ref: myElementRef} = useMyCustomHook<HTMLDivElement>() return <div ref={myElementRef}>A Div</div> }