React native orientation 屏幕旋转监听

android 和 iOS 都有在全局设置中固定屏幕方向的办法,但这样不是特别理想,因为项目中,在不同页面可能会需要横屏或竖屏,此时就可以使用 react-native-orientation ,这个扩展可以动态的锁定/解锁屏幕方向,或设置为指定的方向。

yarn add react-native-orientation

安装完之后二选一 (这个是 rn 安装原生组件的通用命令)

  • rn 6.0 之前的执行 react-native link react-native-orientation
  • rn 6.0 之后执行 cd ios && pod install && cd ..

    详情可参考 官方介绍 这篇文章

    android 打开 android/app/src/main/java/com/[project]/MainActivity.java

    // for react-native-orientation import android.content.Intent; import android.content.res.Configuration; public class MainActivity extends ReactActivity { // for react-native-orientation @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); Intent intent = new Intent("onConfigurationChanged"); intent.putExtra("newConfig", newConfig); this.sendBroadcast(intent);

    iOS 打开 ios/[project]/AppDelegate.m

    // for react-native-orientation #import "Orientation.h" @implementation AppDelegate // for react-native-orientation - (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window { return [Orientation getOrientation];