React Native(七):Android雙擊Back鍵退出應用
阿新 • • 發佈:2019-02-07
歡迎一起來學習React Native,QQ群:672509442
廢話
這是個很常用的小功能,做開發很實用喲
先上程式碼
import {......, BackAndroid, ToastAndroid} from 'react-native';
componentWillMount(){
BackAndroid.addEventListener('hardwareBackPress', this.onBackAndroid);
}
componentWillUnmount() {
BackAndroid.removeEventListener('hardwareBackPress' , this.onBackAndroid);
}
onBackAndroid = () => {
if (this.lastBackPressed && this.lastBackPressed + 2000 >= Date.now()) {
//最近2秒內按過back鍵,可以退出應用。
return false;
}
this.lastBackPressed = Date.now();
ToastAndroid.show('再按一次退出應用', ToastAndroid.SHORT);
return true ;
};
在componentWillMount()和componentWillUnmount()方法中監聽back點選事件,然後自定義onBackAndroid()方法,監聽兩次點選的時間間隔
上個效果圖
自己寫的demo中用到,其他的東西請自行忽略