Handling back button in React Native, Navigator on Android

前端 未结 6 806
旧巷少年郎
旧巷少年郎 2021-02-01 14:45

I have a Navigator in an Android react native application.

I\'m using navigator.push() to navigate to a different page. It would seem natural t

6条回答
  •  无人及你
    2021-02-01 15:28

    In order to clean the code using my knowledge and previous answers, here is how it should look like:

    import { ..., Navigator, BackAndroid } from 'react-native';
    
    componentDidMount() {
      BackAndroid.addEventListener('hardwareBackPress', this.handleBack);
    }
    
    componentWillUnmount() {
      //Forgetting to remove the listener will cause pop executes multiple times
      BackAndroid.removeEventListener('hardwareBackPress', this.handleBack);
    }
    
    handleBack() {
      if (this.navigator && this.navigator.getCurrentRoutes().length > 1){
        this.navigator.pop();
        return true; //avoid closing the app
      }
    
      return false; //close the app
    }
    

提交回复
热议问题