How to handle exit app in one screen not in the whole app - React Native?

后端 未结 2 726
情歌与酒
情歌与酒 2021-01-05 18:23

I have some issue with BackHandler, the issue is

when running the app and go to the let\'s say Sign Up screen and touch the back in my mobile they w

相关标签:
2条回答
  • 2021-01-05 18:44

    You have to get the navigation object of your ROOT navigator by calling dangerouslyGetParent recursively

    For Example If your have that heirarchy:

    • BottomTabs (TabNavigator)

      • Browser (StackNavigator)
      • Settings (StackNavigator)
        • About (Screen)

    And you want to get the current routeName in your androidBackHandler which is wired in your Browser screen, then you should get the navigation object of your BottomTabs by calling dangerouslyGetParent twice (which is the depth of your navigation tree):

    const bottomTabsNavigation = navigation
          .dangerouslyGetParent()
          .dangerouslyGetParent();
    

    If you tried to console.log your bottomTabsNavigation when you're on About screen, you should see something like that

    0 讨论(0)
  • 2021-01-05 19:04

    You can check for the screen has been focused prior to call the alert instead of checking the routeName from navigation.

    the updated code might look like this.

    if (this.props.navigation.isFocused()) {
        Alert.alert(
        "Exit App",
        "Do you want to exit?",
        [
          {
            text: "No",
            onPress: () => console.log("Cancel Pressed"),
            style: "cancel"
          },
          { text: "Yes", onPress: () => BackHandler.exitApp() }
        ],
        { cancelable: false }
        );
    }
    
    0 讨论(0)
提交回复
热议问题