javascript - 属性 getBoundingClientRect 在类型 ParentNode 上不存在
试图像这样使用 getBoundingClientRect:
const menuWrapper = useRef<HTMLElement>(null);
const parentNode = menuWrapper?.current?.parentNode;
const { top, left, height, width } = parentNode?.getBoundingClientRect();
return (
<div ref={menuWrapper}>
...
</div>
)
但目前无法通过 TypeScript 错误:Property 'getBoundingClientRect' does not exist on type 'ParentNode'. 有谁知道解决这个方法吗?
答案#1
尝试使用 parentElement 而不是 parentNode。
const parentEl = menuWrapper?.current?.parentElement;
你也可以看看这个来理解其中的区别。
但无论如何,既然你在使用可选链,这意味着一切都可能是 undefined,你不能像这样使用 top、left、height 和 width。至少你需要添加类似这样的东西
if (!parentEl) {
return;
}
在解构之前。
