react-native实践日记--4.react-native Android回退键,再按一次退出应用

react-native开发Android App,实现回退键返回上一个页面,直至没有历史页面,提示“再按一次退出应用”

首先引入相关api,BackHandler 用于监听安卓设备上的后退按钮事件,设置firstTime默认为0,点击回退按钮,判断当前页面是否为最后一级页面,即没有其他历史页面,且当前时间与上一次点击回退的历史时间间隔大于2秒,则退出App。

import { BackHandler,ToastAndroid } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';


constructor(props) {
    super(props);
    this.state = {
      currentStateRoute: [],
      firstTime: 0, //记录点击Android物理返回按键的时间
    };
  }

componentDidUpdate (prevProps, prevState, snapshot) {
//绑定监听后退事件
    BackHandler.addEventListener(
        'hardwareBackPress',
        this.onBackButtonPressAndroid
      );
  }

componentWillUnMount () {
    AppState.removeEventListener('change', this.handleAppStateChange);
    BackHandler.removeEventListener(
      'hardwareBackPress',
      this.onBackButtonPressAndroid,
    );
  }

onBackButtonPressAndroid = () => {
    if (this.state.currentStateRoute.length == 1) {
      if (new Date().getTime() - this.state.firstTime > 2 * 1000) {
        this.state.firstTime = new Date().getTime();
        ToastAndroid.show('再按一次退出应用', ToastAndroid.SHORT);
        return true;
      } else {
        BackHandler.exitApp();
      }
    } else {
      return false;
    }
    return false;
  };

onStateChange = state => {
    console.log('onStateChange', state);
    this.setState({
      currentStateRoute: state.routes || [],
    });
  };

render () {
    return (
      <RootSiblingParent>
        <StatusBar
          backgroundColor="#0cb3a7"
          barStyle="light-content"
          translucent
        />
        <ApplicationProvider mapping={mapping} theme={theme}>
          <NavigationContainer 
              onStateChange={this.onStateChange.bind(this)}
            />
        </NavigationContainer>
      </RootSiblingParent>
    );
  }

这里注意,历史页面的记录,通过onStateChange回调事件来获取

你可能感兴趣的:(android,react,native,react.js,前端框架,reactnative)