在 ReactJS 中获取视口/窗口高度 [英] Get viewport/window height in ReactJS

查看:119
本文介绍了在 ReactJS 中获取视口/窗口高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

window.innerHeight()

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

ReactDOM.findDomNode()

仅适用于创建的组件.然而,对于 documentbody 元素而言,情况并非如此,这可能会为我提供窗口的高度.

解决方案

class AppComponent extends React.Component {构造函数(道具){超级(道具);this.state = {height: props.height};}componentWillMount(){this.setState({height: window.innerHeight + 'px'});}使成为() {//渲染你的组件...}}

<块引用>

设置道具

AppComponent.propTypes = {高度:React.PropTypes.string};AppComponent.defaultProps = {高度:'500px'};

<块引用>

视口高度现在在渲染模板中作为 {this.state.height} 提供

How do I get the viewport height in ReactJS? In normal JavaScript I use

window.innerHeight()

but using ReactJS, I'm not sure how to get this information. My understanding is that

ReactDOM.findDomNode()

only works for components created. However this is not the case for the document or body element, which could give me height of the window.

解决方案

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...
  }
}

Set the props

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

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

viewport height is now available as {this.state.height} in rendering template

这篇关于在 ReactJS 中获取视口/窗口高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆