far*_*zad 6 javascript typescript reactjs getboundingclientrect react-dom
我已经构建了一个组件,它将根据其在窗口中的尺寸和位置来确定其打开方向。我在 react-dom 节点上使用了 getBoundingClientRect() 函数。现在我已经更新了一些项目包,包括 react 和 react-dom 到 16.3.2。现在我得到一个编译错误:
Property 'getBoundingClientRect' does not exist on type 'Element | Text'
Run Code Online (Sandbox Code Playgroud)
这是使用此功能的一段代码:
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);
Run Code Online (Sandbox Code Playgroud)
任何实现此功能的帮助或建议将不胜感激。
Edit2:这个问题的原因是更新@types/react-dom 到 16.0.5 版本。
该getBoundingClientRect函数仅存在于Element类中,而不存在于Text,因此您需要像这样转换元素的类型:
const node = ReactDOM.findDOMNode(this.containerElement) as Element
Run Code Online (Sandbox Code Playgroud)
另一种更安全的方法是在运行时检查实例类型,typescript 会在检查后智能地转换类型。但是正如您所看到的,对于这种情况,它可能有点不必要的冗长:
const node = ReactDOM.findDOMNode(this.containerElement)
// ...
if (!(node instanceof Element)) return
// type of node should be Element
Run Code Online (Sandbox Code Playgroud)
无论哪种方式,都可以随心所欲。