我希望在状态更新后获得div的高度。
我的代码如下:
const FEATURES = ['feature1', 'feature2', 'feature3', 'feature4', 'feature5', 'feature6']
const CHECKS = ['check1', 'check2', 'check3', 'check4', 'check5', 'check6', 'check7', 'check8', 'check9', 'check10']
class Test extends React.Component {
constructor(props){
super(props);
this.state = {
checksView: false,
}
}
componentDidMount(){
let height = document.getElementById("view").clientHeight;
console.log(height);
}
changeView(view, event){
event.preventDefault();
if(view === "specs"){
this.setState({checksView: false});
}else{
this.setState({checksView: true});
}
}
renderContent(){
if(this.state.checksView){
return (
<div id="view">
{CHECKS.map(check => <div>{check}</div>)}
</div>
)
}else{
return (
<div id="view">
{FEATURES.map(check => <div>{check}</div>)}
</div>
)
}
}
render(){
return (
<div>
<div>
<div style={{float: "left", marginRight: 10}} onClick={this.changeView.bind(this, "specs")}>Specs</div>
<div style={{float: "left"}} onClick={this.changeView.bind(this, "checks")}>Checks</div><br />
</div>
{this.renderContent()}
</div>
)
}
}
React.render(<Test />, document.getElementById('container'));
在console.log
componentDidMount
中我看到相同的值。
但是checks
的div比具有功能的div更高,但检查的内容没有加载,我仍然得到了功能div的高度。
任何想法如何在状态更新后等待内容加载然后检查它的高度?
答案 0 :(得分:0)
在状态改变后做点什么。
this.setState({checksView: false}, function() {
//do something
});
更多细节
getHeight() {
let height = document.getElementById("view").clientHeight;
console.log(height);
}
changeView(view, event){
event.preventDefault();
if(view === "specs"){
this.setState({checksView: false}, function() {
this.getHeight();
});
}else{
this.setState({checksView: true}, function() {
this.getHeight();
});
}
}