Handling back button in React Native, Navigator on Android

前端 未结 6 844
旧巷少年郎
旧巷少年郎 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条回答
  •  猫巷女王i
    2021-02-01 15:25

    Not sure when the API changed but as of react native 0.31 (potentially earlier versions as well) BackAndroid is a component that must be imported from react-native:

    import {..., BackAndroid} from 'react-native'

    Also be sure to remove the listener on componentWillUnmount:

    componentWillUnmount(){
        BackAndroid.removeEventListener('hardwareBackPress', () => {
            if (this.navigator && this.navigator.getCurrentRoutes().length > 1) {
                this.navigator.pop();
                return true;
            }
            return false;
        });
    }
    

    *UPDATE: In react native 0.44 this module has been renamed to BackHandler. Navigator has also been officially deprecated but can still be found here: https://github.com/facebookarchive/react-native-custom-components

    import { BackHandler } from 'react-native';
    

提交回复
热议问题