1. 程式人生 > >react_native 物理鍵back或者回退鍵的單擊返回和雙擊退出app功能

react_native 物理鍵back或者回退鍵的單擊返回和雙擊退出app功能

公司app開發,react-native(android)要實現點選手機物理鍵back返回和退出app功能,本人也是小白,不是很懂,但是作為一個app,這是基本功能,所以必須實現。下面兩個方案的coding中有什麼寫的不好的地方請多多包涵,親測沒問題,兩個方法都跑的通,開始程式碼......

import { ToastAndroid,
  AppState,
  BackHandler,
  Platform,StyleSheet,View,Text,ScrollView,AsyncStorage } from 'react-native';

方法一:

將程式碼寫到app.js主入口檔案中

const firstClick = 0;(定義一個常量,寫在哪裡都懂)

constructor(props) {
        super(props);
        this.state = {
            selectedTab: 'home',
        }
        this.handleBack = this.handleBack.bind(this);
    }

    componentDidMount() {
        BackHandler.addEventListener('hardwareBackPress', this.handleBack)
    }

    componentWillUnmount() {
        BackHandler.removeEventListener('hardwareBackPress', this.handleBack)
    }

    handleBack = () => {
        var timestamp = (new Date()).valueOf();
        if (timestamp - firstClick > 1000) {
            firstClick = timestamp;
            return false;
        } else {
            ToastAndroid.show('退出程式', ToastAndroid.SHORT);
            BackHandler.exitApp();
            return true;
        }

    }

方法二:這個方法借鑑網上的coding並且個人做了修改,原方法並不能退出,我是結合了當前router所在位置做判斷,我用的是react-native-router-flux中的scence,並且限制Actions.state.index來實現頁面的首頁雙擊退出其他頁面back正常返回。

將程式碼寫到app.js主入口檔案中

//   constructor(props){
//   super(props);
//   this.state = {
//     test: "wbd",
//   };
// }
// componentDidMount() {
//     if(Platform.OS === 'android') BackHandler.addEventListener('hardwareBackPress', this._onBackPressed);
//     AppState.addEventListener('change', this._onAppStateChanged);
//   }

//   //元件解除安裝之前移除監聽
//   componentWillUnmount() {
//     if(Platform.OS === 'android') BackHandler.removeEventListener('hardwareBackPress', this._onBackPressed);
//     AppState.removeEventListener('change', this._onAppStateChanged);
//   }

//   _onBackPressed() {
//     lastBackPressed = Date.now();
//     if (Actions.state.index == 0) {
//         if (lastBackPressed && lastBackPressed + 2000 >= Date.now()) {
//         BackHandler.exitApp();
//       }
      
//       ToastAndroid.show('退出應用', ToastAndroid.SHORT);
//       return true;
//     };
    
//   }

//   _onAppStateChanged() {
//     switch (AppState.currentState) {
//       case "active":
//         console.log("active");
//         break;
//       case "background":
//         console.log("background");
//         break;
//       default:

//     }
//   }

ok,兩個簡單的實現方法都寫了,可以考慮試試好不好用...