RN监听返回键

BackAndroid已经被废弃。改用BackHandler
关键代码

componentWillMount() {
        if (Platform.OS === 'android') {
            this.listener = BackHandler.addEventListener('hardwareBackPress', this.onBackAndroid);
        }
    }

    componentWillUnmount() {
        if (Platform.OS === 'android') {
            this.listener.remove('hardwareBackPress');
        }
    }

    onBackAndroid = () => {
        const navigator = this.refs.navigator;//**************************
        const routers = navigator.getCurrentRoutes();
        console.log('当前路由长度:' + routers.length);
        if (routers.length > 2) {
            navigator.pop();
            return true;//接管默认行为
        } else {
            //到了主页了
            if (this.lastBackPressed && this.lastBackPressed + 2000 >= Date.now()) {
                //最近2秒内按过back键,可以退出应用。
                return false;
            }
            this.lastBackPressed = Date.now();
            ToastAndroid.show('再按一次退出应用', ToastAndroid.SHORT);
            return true;
        }
        // return false;//默认行为

    };

上面用到了this.refs.navigator,贴一下代码

render() {
        return (
            name: 'TestComp', component: TestComp}}
                //配置场景
                ref="navigator"
                configureScene={
                    (route) => {
                        return NavigationExperimental.Navigator.SceneConfigs.FloatFromRight;
                    }
                }
                renderScene={
                    (route, navigator) => {
                        let Component = route.component;
                        return 
                    }
                }/>
        );
    }

你可能感兴趣的:(react-native)