React Native入门篇—BackHandler安卓返回键判断 返回页面或关闭APP

注意:未经允许不可私自转载,违者必究

React Native官方文档:https://reactnative.cn/docs/backhandler/

项目地址GitHub地址:https://github.com/zhouwei1994/nativeCase.git

安卓返回键配置

本项目是用react-navigation来做路由,路由长度需要由redux来托管,所以下面代码会和react-navigation  redux关联

react-navigation配置请参考:https://blog.csdn.net/weixin_40614372/article/details/86237863

react-redux配置请参考:https://blog.csdn.net/weixin_40614372/article/details/86288783

import React, { Component } from 'react';
import { ToastAndroid, BackHandler, StatusBar } from 'react-native';
import { NavigationActions } from "react-navigation";
import { Provider } from 'react-redux';
import { store, AppWithNavigationState } from './store/index';
//最后一次按返回的时间
let lastBackPressed = 0;
export default class Root extends React.Component {
  componentDidMount() {
    BackHandler.addEventListener("hardwareBackPress", this.onBackPress);
  }
  componentWillUnmount() {
    BackHandler.removeEventListener("hardwareBackPress", this.onBackPress);
  }
  //安卓返回键关闭APP
  onBackPress = () => {
    if (store.getState().nav.index === 0) {
      let now = new Date().getTime();
      if (now - lastBackPressed < 2500) {
        return false;
      }
      lastBackPressed = now;
      ToastAndroid.show('再点击一次退出应用', ToastAndroid.SHORT);
      return true;
    }
    store.dispatch(NavigationActions.back());
    return true;
  };
  render() {
    return (
      
        
      
    );
  }
}

项目地址GitHub地址:https://github.com/zhouwei1994/nativeCase.git

注意:未经允许不可私自转载,违者必究

你可能感兴趣的:(安卓返回键,React,Native,BackHandler)