测量语义反应UI中元素的高度



我正在尝试测量组件的高度,如果我尝试获取参考并找到偏僻的人,则ref始终恢复为无效。因此,如何测量反应语义 - UI组件的高度。

<Container ref={rf=>this.container=rf} style={{overflowY:"auto"}}>
    <Item.Group divided >
        <ItemList items={items}></ItemList>
    </Item.Group>
</Container>
在这里

还有哪些其他方法可以测量反应语义 - UI组件的高度?

@bogdan-surai,您可以测试以下代码:

  componentDidMount() {
    const container = this.container;
    if (!container) {
      return;
    }
    const specs = container.getBoundingClientRect();
    console.log(specs);
  }

@salman.zare是的。当componentDidMount刚刚开火时,它行不通。我想原因是当时的高度确实等于0。但是我们可以运行setInterval以后几次获得高度。

此代码对我有用

  componentDidMount() {
        this.intervalId = setInterval(() => {
           const container = this.container;
           if (!container) {
              return;
           }
           const specs = container.getBoundingClientRect();
           console.log(specs);
           console.log(this.scrollComponent.offsetHeight);
           this.setState(() => ({ height: specs.height }));
        }, 100);

    }

然后我在浏览器的控制台中看到了它。

DOMRect {x: 0, y: 120, width: 693, height: 0, top: 120, …}
DOMRect {x: 0, y: 16, width: 678, height: 4068, top: 16, …}

您应该在componentDidMountcomponentDidUpdate方法中使用this.container.offsetHeight

可以将您的组件包装到<div ref={...}></div>中。然后,您可以获得div的高度。如果您的较高组件没有边距,则DIV的高度和组件的高度将相同。

注意:

  1. 当在称为类的自定义组件上使用REF属性时,Ref回调将接收组件的已安装实例作为其参数。

  2. 当在HTML元素上使用REF属性时,Ref回调将接收基础DOM元素作为其参数。

  3. 可能不会使用功能组件上的ref属性,因为它们没有实例

从1和2返回的值具有不同的属性和方法。有一个doc https://reactjs.org/docs/refs-and-the-dom.html

最新更新