getBoundingClientRect 不存在

问题描述 投票:0回答:1

我构建了一个组件,它将根据其尺寸和在窗口中的位置确定其打开方向。我在react-dom节点上使用了getBoundingClientRect()函数。现在我已经更新了一些项目包,包括react和react-dom到16.3.2。现在我得到一个编译错误:

Property 'getBoundingClientRect' does not exist on type 'Element | Text'

这是使用此功能的一段代码:

const node = ReactDOM.findDOMNode(this.containerElement);

if (!node) {
  return;
}

let vertical: Vertical_Direction;
if (verticalDirection === Vertical_Direction.DOWN_UP) {
  const windowHeight = window.innerHeight;
  const height: number = Math.min(containerHeight, node.getBoundingClientRect().height);

任何实现此功能的帮助或建议将不胜感激。

Edit2:此问题的原因是将@types/react-dom更新到16.0.5版本。

javascript reactjs typescript react-dom getboundingclientrect
1个回答
14
投票

getBoundingClientRect
函数仅存在于
Element
类中,而不存在于
Text
中,因此您需要像这样转换元素的类型:

const node = ReactDOM.findDOMNode(this.containerElement) as Element

另一种更安全的方法是在运行时检查实例类型,TypeScript 将在检查后智能地转换类型。但正如您所看到的,对于这种情况,它可能有点不必要的冗长:

const node = ReactDOM.findDOMNode(this.containerElement)

// ...

if (!(node instanceof Element)) return

// type of node should be Element

无论哪种方式,随你喜欢。

© www.soinside.com 2019 - 2024. All rights reserved.