Handling back button in React Native, Navigator on Android

前端 未结 6 799
旧巷少年郎
旧巷少年郎 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:41

    Don't forget bind [this]

    The correct answer should be:

    export default class MyPage extends Component {
      constructor(props) {
        super(props)
        this.navigator = null;
    
        this.handleBack = (() => {
          if (this.navigator && this.navigator.getCurrentRoutes().length > 1){
            this.navigator.pop();
            return true; //avoid closing the app
          }
    
          return false; //close the app
        }).bind(this) //don't forget bind this, you will remember anyway.
      }
    
      componentDidMount() {
        BackAndroid.addEventListener('hardwareBackPress', this.handleBack);
      }
    
      componentWillUnmount() {
        BackAndroid.removeEventListener('hardwareBackPress', this.handleBack);
      }
    
      render() {
        return (
           {this.navigator = navigator}}
      ...
    

提交回复
热议问题