我正在尝试测量组件的高度,如果我尝试获取参考并找到偏僻的人,则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, …}
您应该在componentDidMount
或componentDidUpdate
方法中使用this.container.offsetHeight
。
可以将您的组件包装到<div ref={...}></div>
中。然后,您可以获得div
的高度。如果您的较高组件没有边距,则DIV的高度和组件的高度将相同。
注意:
-
当在称为类的自定义组件上使用REF属性时,Ref回调将接收组件的已安装实例作为其参数。
-
当在HTML元素上使用REF属性时,Ref回调将接收基础DOM元素作为其参数。
-
您可能不会使用功能组件上的ref属性,因为它们没有实例
从1和2返回的值具有不同的属性和方法。有一个doc https://reactjs.org/docs/refs-and-the-dom.html