React Native - Device back button handling

后端 未结 9 2106
感情败类
感情败类 2020-12-02 18:33

I want to check if there are more than one screens are on stack when device back button is hit. If yes, I want to show previous screen and if no, I want to exit app.

9条回答
  •  既然无缘
    2020-12-02 19:13

    In a case where there are more than one screens stacked in the stack, the default back button behavior in react-native is to navigate back to the previous screen in the stack. Handling the device back button press when having only one screen to exit the app requires a custom setting. Yet this can be achieved without having to add back handling code to each and every screen by modifying the getStateForAction method of the particular StackNavigator's router.

    Suppose you have the following StackNavigator used in the application

    const ScreenStack = StackNavigator(
      {
        'Screen1': {
          screen: Screen1
        },
        'Screen2': {
          screen: Screen2
        },
      },
      {
        initialRouteName: 'Screen1'
      }
    );
    

    The getStateForAction method of the stack navigator's router can be modified as follows to achieve the expected back behavior.

    const defaultStackGetStateForAction =
      ScreenStack.router.getStateForAction;
    
    ScreenStack.router.getStateForAction = (action, state) => {
      if(state.index === 0 && action.type === NavigationActions.BACK){
        BackHandler.exitApp();
        return null;
      }
    
      return defaultStackGetStateForAction(action, state);
    };
    

    the state.index becomes 0 only when there is one screen in the stack.

提交回复
热议问题