使用react js和orientationchange事件时如何检测移动网站的屏幕方向?

新手上路,请多包涵

我想使用所有主要移动浏览器都 支持 的事件 orientationchange 检测屏幕方向变化。

我在 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;

原文由 hitchhiker 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 294
1 个回答
import { useWindowDimensions } from 'react-native';

// In your component:
const { height, width } = useWindowDimensions();
const isPortrait = height > width;

原文由 Dominic 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题