无法将 RefObject<HTMLDivElement> 分配给 RefObject<HTMLElement> 实例

IT技术 reactjs typescript
2021-04-28 11:06:54

在 React 组件中,我想保留对类型不同(div、img 等)的子节点的引用。所以我定义了一个成员变量:

export class MyComp extends Component<IProperties, IState> {

    private triggerRef = React.createRef<HTMLElement>();

...
}

并想用它来保存所需的参考:

    const trigger = <div ref={this.triggerRef} className={className} style={style} />;

虽然,这会产生一个错误:

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>'

该行Type 'RefObject<HTMLElement>' is not assignable to type 'RefObject<HTMLDivElement>'表示这两种 ref 对象类型不兼容,即使HTMLDivElementextends HTMLElement我希望 ref 类型是赋值兼容的,因为它们显然有重叠。

在不更改要使用的成员变量的情况下,这里的正确方法是什么HTMLDivElement

2个回答

这并不是我最初问题的真正答案,而是一个简单的解决方法,它可以很好地完成工作:

const trigger = <div 
    ref={this.triggerRef as React.RefObject<HTMLDivElement>}
    className={className}
    style={style}
/>

对于所有因为在编写自定义钩子用 DOM 元素做某事时遇到这个问题而来到这个线程的人,以下工作:

function useMyCustomHook<T extends HTMLElement>{
    const myRef = useRef<T>(null)

    // do something with the ref, e.g. adding event listeners

    return {ref: myRef}
}

function MyComponent(){
    const {ref: myElementRef} = useMyCustomHook<HTMLDivElement>()

    return <div ref={myElementRef}>A Div</div>
}