无法将引用对象<HTMLDivElement>分配给引用对象<HTMLElement>实例



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

export class MyComp extends Component<IProperties, IState> {
private triggerRef = React.createRef<HTMLElement>();
...
}

并想用它来保存所需的ref:

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对象类型不兼容,即使HTMLDivElement扩展了HTMLElement。我希望ref类型是赋值兼容的,因为它们显然有重叠。

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

这并不是我最初问题的答案,而是一个简单的解决方法,它很好地完成了任务:

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

更改

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

到特定元素类型:

private triggerRef = React.createRef<HTMLDivElement>();`

然后ref={this.triggerRef}将工作(而不需要像ref={this.triggerRef as React.RefObject<HTMLDivElement>}那样进行投射(。

这对我有效

const refPanel_1 = useRef<null | HTMLDivElement>(null);

最新更新