react-native 如何切换横竖屏?

目前代码

import Orientation from 'react-native-orientation';

<TouchableOpacity
onPress={() => {
  const initial = Orientation.getInitialOrientation();
  if (initial === 'PORTRAIT') {
    // 当前竖屏
    Orientation.lockToLandscapeLeft();
  } else {
    // 当前非竖屏
    Orientation.lockToPortrait();
  }
}}
style={{alignSelf: 'center', marginLeft: 10, marginRight: 10}}>
    // ....
</TouchableOpacity>

但是这么写我发现他始终只能从竖屏点击后到横屏
但是竖屏点击后, 再也没法从竖屏回到横屏
请问这是为什么呢?

环境:

  • 雷电模拟器
阅读 5.3k
2 个回答

建议使用react-native-orientation-locker 这个库

react-native-orientation bug 比较多

getInitialOrientation是在开头用的,并不是实时的
你打印一下 initial 的值 就知道了

通过

Orientation.addOrientationListener(orientation=>{
    console.log(orientation)
});

这个监听获取确切的是否横屏

不在模拟器的环境也不行吗?

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