美文网首页
React Navigation Android 返回键事件处理

React Navigation Android 返回键事件处理

作者: Thelastgame | 来源:发表于2019-01-17 16:50 被阅读21次

实际开发中有这么一个需求,当停留在首页的时候 点击 Android的返回键,提示再次点击退出,直接上代码

  import React from "react";
  import { BackHandler } from "react-native";
  class ScreenWithCustomBackBehavior extends React.Component {
    _didFocusSubscription;
    _willBlurSubscription;
    constructor(props) {
      super(props);
    this._didFocusSubscription = props.navigation.addListener('didFocus', payload =>
      BackHandler.addEventListener('hardwareBackPress', this.onBackButtonPressAndroid)
  ) ;
}

componentDidMount() {
    this._willBlurSubscription = this.props.navigation.addListener('willBlur', payload =>
     BackHandler.removeEventListener('hardwareBackPress', this.onBackButtonPressAndroid)
  );
}

onBackButtonPressAndroid = () => {
    if (判断条件) {
    //需要操作的事件(如:再次点击退出应用)
  return true;
    } else {
  return false;
  }
} ;

componentWillUnmount() {
  this._didFocusSubscription && this._didFocusSubscription.remove();
  this._willBlurSubscription && this._willBlurSubscription.remove();
}

render() {
// ...
  }
}

相关文章

网友评论

      本文标题:React Navigation Android 返回键事件处理

      本文链接:https://www.haomeiwen.com/subject/megidqtx.html