1.引入BackHandler 从react-native中
2.在componentDidMount中添加下面那行监听代码
this.backHandler = BackHandler.addEventListener('hardwareBackPress', this.handleBackPress);
3.在componentWillUnmount添加
componentWillUnmount() {
this.backHandler.remove()
}
4.在handleBackPress函数中写相关返回逻辑
handleBackPress = () => {
Actions.pop(); // 跳转,可以跳转到想去的页面或位置,根据react-native-router-flux组件的方法
console.log("wo handle back press detail")
// //this.goBack(); // works best when the goBack is async
return true;
}
如果想要点2次退出应用:可以这么写
handleBackPress = () => {
if (this.lastBackPressed && this.lastBackPressed + 2000 >= Date.now()) {
//最近2秒内按过back键,可以退出应用。
BackHandler.exitApp();//退出整个应用
return false
}
this.lastBackPressed = Date.now();
console.log('再按一次要退出了')
ToastAndroid.show('再按一次退出应用', ToastAndroid.SHORT);
return true;
}
官网:
https://facebook.github.io/react-native/docs/backhandler.html