问题
I've an React Native Expo app running on both iOS and Android using Stack Navigation with two views. The first view is locked to portrait screen orientation
export class HomeScreen extends Component {
componentWillMount() {
ScreenOrientation.lockAsync(ScreenOrientation.OrientationLock.PORTRAIT_UP);
}
render() {...
}
}
The second view should be available in both portrait and landscape screen orientation:
export class DetailScreen extends Component {
componentDidMount() {
ScreenOrientation.lockAsync(
ScreenOrientation.OrientationLock.ALL_BUT_UPSIDE_DOWN
);
}
async componentWillUnmount() {
await ScreenOrientation.lockAsync(
ScreenOrientation.OrientationLock.PORTRAIT_UP
);
}
render() {...
}
}
This is working almost as expected, but I have two issues:
- When second view (
DetailScreen
) is in landscape and the back button is pressed, the first view (HomeScreen) is briefly shown in landscape orientation before rotation back to the portrait orientation. Is it possible to ensure that the device has rotated to portrait before navigating back? I tried doing that usingasync await
in thecomponentWillUnmount
method inside theDetailScreen
, but the screen is still in landscape when the component is unmounted.
- Using gestures I'm able to navigate back to the
HomeScreen
. But doing this gesture when theDetailScreen
is shown in landscape, theHomeScreen
is shown in landscape as well. How can I handle this? Is it possible somehow to disable this gesture inside theDetailScreen
when in landscape orientation?
The example is available in this Expo Snack: https://snack.expo.io/HJ_nhkQKH
回答1:
I updated the expo snack for your question: https://snack.expo.io/BJfXseXYB
Part 1. using NavigationEvents - onWillFocus
Part 2:
const RootStack = createStackNavigator(
{
Home: {
screen: HomeScreen,
navigationOptions: {
gesturesEnabled: true,
},
},
DetailView: {
screen: DetailScreen,
navigationOptions: {
gesturesEnabled: false,
},
},
},
{
initialRouteName: 'Home',
}
);
来源:https://stackoverflow.com/questions/58389132/how-to-handle-locked-orientation-using-react-native-stack-navigation