首页 > 解决方案 > 如何使用 React Native Stack Navigation 处理锁定的方向

问题描述

我有一个在 iOS 和 Android 上运行的 React Native Expo 应用程序,使用 Stack Navigation 和两个视图。第一个视图被锁定为纵向屏幕方向

export class HomeScreen extends Component {
  componentWillMount() {
    ScreenOrientation.lockAsync(ScreenOrientation.OrientationLock.PORTRAIT_UP);
  }

  render() {...
  }
}

第二个视图应该在纵向和横向屏幕方向都可用:

export class DetailScreen extends Component {
  componentDidMount() {
    ScreenOrientation.lockAsync(
      ScreenOrientation.OrientationLock.ALL_BUT_UPSIDE_DOWN
    );
  }

  async componentWillUnmount() {
    await ScreenOrientation.lockAsync(
      ScreenOrientation.OrientationLock.PORTRAIT_UP
    );
  }

  render() {...
  }
}

这几乎按预期工作,但我有两个问题:

  1. 当第二个视图 ( DetailScreen) 处于横向并按下返回按钮时,第一个视图 (HomeScreen) 会在旋转回纵向之前短暂地以横向显示。是否可以确保设备在返回之前已旋转为纵向?我尝试在内部async awaitcomponentWillUnmount方法中使用它DetailScreen,但是当组件被卸载时屏幕仍然是横向的。

HomeSceen 以横向简要显示

  1. 使用手势我可以导航回HomeScreen. DetailScreen但是当以横向显示时,执行此手势,也以横向HomeScreen显示。我该如何处理?是否有可能以某种方式DetailScreen在横向时禁用此手势?

在此处输入图像描述

该示例可在此 Expo Snack 中找到: https ://snack.expo.io/HJ_nhkQKH

标签: react-nativereact-navigationexpo

解决方案


我为您的问题更新了世博小吃: https ://snack.expo.io/BJfXseXYB

第 1 部分。使用 NavigationEvents - onWillFocus

第2部分:

const RootStack = createStackNavigator(

  {
    Home: {
      screen: HomeScreen,
      navigationOptions: {
        gesturesEnabled: true,
      },
    },

    DetailView: {
      screen: DetailScreen,
      navigationOptions: {
        gesturesEnabled: false,
      },
    },
  },

  {
    initialRouteName: 'Home',
  }
);

推荐阅读