在React JS中更新状态后获取div的高度

时间:2018-01-15 08:13:09

标签: reactjs

我希望在状态更新后获得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的高度。

任何想法如何在状态更新后等待内容加载然后检查它的高度?

Here is the fiddle.

1 个答案:

答案 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();
        });
    }
}