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