【发布时间】:2016-05-11 06:22:43
【问题描述】:
如何在 React 渲染元素后获取该元素的高度?
HTML
<div id="container">
<!-- This element's contents will be replaced with your component. -->
<p>
jnknwqkjnkj<br>
jhiwhiw (this is 36px height)
</p>
</div>
ReactJS
var DivSize = React.createClass({
render: function() {
let elHeight = document.getElementById('container').clientHeight
return <div className="test">Size: <b>{elHeight}px</b> but it should be 18px after the render</div>;
}
});
ReactDOM.render(
<DivSize />,
document.getElementById('container')
);
结果
Size: 36px but it should be 18px after the render
它在渲染之前计算容器高度(36px)。我想在渲染后获得高度。在这种情况下,正确的结果应该是 18px。 jsfiddle
【问题讨论】:
-
这不是一个反应问题,而是一个 Javascript 和 DOM 问题。您应该尝试找出应该使用哪个 DOM 事件来找到元素的最终高度。在事件处理程序中,您可以使用
setState将高度值分配给状态变量。 -
现在,我强烈建议只使用 react-use 的 useMeasure 挂钩来代替。
标签: javascript reactjs