react单页应用不想出现竖直滚动条的解决方案

针对改变浏览器宽度,浏览器底部出现滚动条时的情况,解决方案是设置事件监听,根据浏览器的可视区域高度实时更新页面的高度。

步骤1:在state中初始化页面高度为window.document.body.clientHeight(注:这里的clientHeight是去除页面底部滚动条高度的浏览器可视区域高度,应与window.innerHeight区分开)

state = {height:  window.document.body.clientHeight} 

步骤2:写一个方法用来更新height

reloadHeight = () => {
    this.setState({height: window.document.body.clientHeight})
  };

步骤3:在componentDidMount事件中添加一个设置高度的事件监听

componentDidMount() {
    window.addEventListener('resize', this.reloadHeight);
}

步骤4:在组件即将销毁时移除这个监听事件

componentWillUnmount() {
    window.removeEventListener('resize', this.reloadHeight)
  }
步骤5:在需要设置高度的标签上引用this.state.height就可以了

猜你喜欢

转载自blog.csdn.net/hfhwfw161226/article/details/79976137