6

我已经构建了一个组件,它将根据它在窗口中的尺寸和位置来确定它的打开方向。我在 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 版本。

4

1 回答 1

9

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

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

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

const node = ReactDOM.findDOMNode(this.containerElement)

// ...

if (!(node instanceof Element)) return

// type of node should be Element

不管怎样,随心所欲。

于 2018-04-28T07:51:26.473 回答