在React呈现元素之后,我如何获得元素的高度?
<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
它正在计算呈现之前的容器高度(36 It)。我想得到渲染后的高度。在这种情况下,正确的结果应该是18 in。小提琴
发布于 2016-02-02 12:46:57
参见这小提琴(实际上更新了您的小提琴)
您需要连接到componentDidMount
,它是在呈现方法之后运行的。在那里,你得到了元素的实际高度。
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>
发布于 2019-02-23 12:57:47
对于那些对使用react hooks
感兴趣的人来说,这可能会帮助你开始工作。
import React, { useState, useEffect, useRef } from 'react'
export default () => {
const [height, setHeight] = useState(0)
const ref = useRef(null)
useEffect(() => {
setHeight(ref.current.clientHeight)
})
return (
<div ref={ref}>
{height}
</div>
)
}
发布于 2017-05-18 05:37:54
下面是使用ES6的最新参考示例。
请记住,我们必须使用反应类组件,因为我们需要访问Lifecycle componentDidMount()
,因为只有在元素在DOM中呈现后才能确定它的高度。
import React, {Component} from 'react'
import {render} from 'react-dom'
class DivSize extends Component {
constructor(props) {
super(props)
this.state = {
height: 0
}
}
componentDidMount() {
const height = this.divElement.clientHeight;
this.setState({ height });
}
render() {
return (
<div
className="test"
ref={ (divElement) => { this.divElement = divElement } }
>
Size: <b>{this.state.height}px</b> but it should be 18px after the render
</div>
)
}
}
render(<DivSize />, document.querySelector('#container'))
您可以在这里找到正在运行的示例:https://codepen.io/bassgang/pen/povzjKw
https://stackoverflow.com/questions/35153599
复制相似问题