最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - getBoundingClientRect does not exist - Stack Overflow

programmeradmin3浏览0评论

I have built a ponent that will determine its opening direction based on its dimension and position in the window. I used getBoundingClientRect() function on a react-dom node. Now i have updated some of project packages including react and react-dom to 16.3.2. Now I get a pile error:

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

here is a piece of code that use this function:

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);

Any help or suggestion to achieve this functionality will be appreciated.

Edit2: the cause of this problem is updating @types/react-dom to 16.0.5 version.

I have built a ponent that will determine its opening direction based on its dimension and position in the window. I used getBoundingClientRect() function on a react-dom node. Now i have updated some of project packages including react and react-dom to 16.3.2. Now I get a pile error:

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

here is a piece of code that use this function:

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);

Any help or suggestion to achieve this functionality will be appreciated.

Edit2: the cause of this problem is updating @types/react-dom to 16.0.5 version.

Share Improve this question edited Mar 4, 2024 at 20:31 Kalnode 11.4k3 gold badges40 silver badges73 bronze badges asked Apr 28, 2018 at 5:58 farzadfarzad 4091 gold badge4 silver badges17 bronze badges 0
Add a ment  | 

1 Answer 1

Reset to default 14

The getBoundingClientRect function only exists on the Element class, and not Text, so you'll need to cast the type of your element like so:

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

An alternative, safer route would be to check the instance type at runtime, and typescript will intelligently cast the type after the check. But as you can see, it might be a little unnecessarily verbose for this case:

const node = ReactDOM.findDOMNode(this.containerElement)

// ...

if (!(node instanceof Element)) return

// type of node should be Element

Either way, go with whatever you prefer.

发布评论

评论列表(0)

  1. 暂无评论