小编典典

在ReactJS中获取视口/窗口高度

reactjs

如何在ReactJS中获得视口高度?在普通的JavaScript中,我使用

window.innerHeight()

但是使用ReactJS,我不确定如何获取此信息。我的理解是

ReactDOM.findDomNode()

仅适用于创建的组件。但是,对于documentor body元素而言并非如此,这可能会给我窗口的高度。


阅读 1639

收藏
2020-07-22

共1个答案

小编典典

class AppComponent extends React.Component {

  constructor(props) {
    super(props);
    this.state = {height: props.height};
  }

  componentWillMount(){
    this.setState({height: window.innerHeight + 'px'});
  }

  render() {
    // render your component...
  }
}

设置道具

AppComponent.propTypes = {
 height:React.PropTypes.string
};

AppComponent.defaultProps = {
 height:'500px'
};

视口高度现在可以在渲染模板中用作{this.state.height}

2020-07-22