ReactJS - 获取元素的高度 [英] ReactJS - Get Height of an element
问题描述
如何在 React 渲染元素后获取元素的高度?
HTML
<!-- 此元素的内容将替换为您的组件.--><p>jnknwqkjnkj
jhiwhiw(这是36px的高度)</p>
ReactJS
var DivSize = React.createClass({渲染:函数(){让 elHeight = document.getElementById('container').clientHeight返回<div className="test">尺寸:<b>{elHeight}px</b>但渲染后应该是 18px
;}});ReactDOM.render(<DivSize/>,document.getElementById('容器'));
结果
Size: 36px 但渲染后应该是 18px
它在渲染前计算容器高度 (36px).我想获得渲染后的高度.在这种情况下,正确的结果应该是 18px.jsfiddle
参见 this fiddle(实际上更新了你的)
您需要挂接在render 方法之后运行的componentDidMount
.在那里,您可以获得元素的实际高度.
var DivSize = React.createClass({getInitialState() {返回{状态:0};},componentDidMount() {const height = document.getElementById('container').clientHeight;this.setState({高度});},渲染:函数(){返回 (<div className="测试">尺寸:<b>{this.state.height}px</b>但渲染后应该是 18px
);}});ReactDOM.render(<DivSize/>,document.getElementById('容器'));
<script src="https://facebook.github.io/react/js/jsfiddle-integration-babel.js"></script><div id="容器"><p>jnknwqkjnkj
jhiwhiw(这是36px的高度)</p><!-- 此元素的内容将替换为您的组件.-->
How can I get the Height of an element after React renders that element?
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')
);
RESULT
Size: 36px but it should be 18px after the render
It's calculating the container height before the render (36px). I want to get the height after the render. The right result should be 18px in this case. jsfiddle
See this fiddle (actually updated your's)
You need to hook into componentDidMount
which is run after render method. There, you get actual height of element.
var DivSize = React.createClass({
getInitialState() {
return { state: 0 };
},
componentDidMount() {
const height = document.getElementById('container').clientHeight;
this.setState({ height });
},
render: function() {
return (
<div className="test">
Size: <b>{this.state.height}px</b> but it should be 18px after the render
</div>
);
}
});
ReactDOM.render(
<DivSize />,
document.getElementById('container')
);
<script src="https://facebook.github.io/react/js/jsfiddle-integration-babel.js"></script>
<div id="container">
<p>
jnknwqkjnkj<br>
jhiwhiw (this is 36px height)
</p>
<!-- This element's contents will be replaced with your component. -->
</div>
这篇关于ReactJS - 获取元素的高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!