使用React JS和DirectionsChange事件时如何在移动网站中检测屏幕方向?

时间:2019-04-13 08:25:19

标签: javascript reactjs dom-events

我想使用事件orientationchange来检测屏幕方向的变化,所有主流移动浏览器都将事件supported

我在componentDidMount中添加了事件侦听器,并从事件回调内部设置了状态。

但是,我看到当事件从纵向更改为横向而首次触发时,状态并未更新为横向。然后,当我将方向从横向更改为纵向时,状态会显示方向为横向。此后,每次我改变方向时,状态总是说与实际方向相反。我不确定是否应该使用某些生命周期反应方法,或者我的检测不好。

我使用Chrome开发人员工具Toggle device toolbar测试了代码。 这是我的代码:

import React from 'react';

class AppInfo extends React.Component {
  state = {
    screenOrientation: 'portrait'
  }

  isPortraitMode = () => {
    console.log(this.state);
    const { screenOrientation } = this.state;
    return screenOrientation === 'portrait';
  }

  setScreenOrientation = () => {
    if (window.matchMedia("(orientation: portrait)").matches) {
      console.log('orientation: portrait');
      this.setState({
        screenOrientation: 'portrait'
      });
    }

    if (window.matchMedia("(orientation: landscape)").matches) {
      console.log('orientation: landscape');
      this.setState({
        screenOrientation: 'landscape'
      });
    }
  }

  componentDidMount() {
    window.addEventListener('orientationchange', this.setScreenOrientation);
  }

  render() {
    console.log(`orientation: from render: isPortraitMode = ${this.isPortraitMode()}`);
    <div>
      Hello
    </div>
  }
}

export default AppInfo;

2 个答案:

答案 0 :(得分:2)

您可以尝试使用“调整大小”事件来触发它,因为某些设备没有提供directionchange事件,但是会触发窗口的调整大小事件。

window.addEventListener("resize", this.setScreenOrientation);

答案 1 :(得分:0)

您的程序运行正常,您只需要这样登录即可:

this.setState({screenOrientation: 'landscape'}, console.log('orientation: landscape'))

其背后的原因是对setState的调用不是同步的,但是setState(updater,callback)是一个异步函数,它将回调作为第二个参数。