首页 > 解决方案 > 无法删除android backHandler

问题描述

我发现这段代码可以处理 android 上的后退按钮:

componentDidMount() {
  this.handleAndroidBackButton ();
}
componentWillUnmount () {
  this.removeAndroidBackButtonHandler();
}
handleAndroidBackButton = () => {
  BackHandler.addEventListener('hardwareBackPress', () => {
    this.showModal1(true);
    return true;
  });
};

removeAndroidBackButtonHandler = () => {
  BackHandler.removeEventListener('hardwareBackPress', () => {});
}

它工作正常,但是当我转到另一个页面时,我仍然有相同的行为。我在stackoverflow上找到了这个:

constructor() {
   this._onBackButton= this._onBackButton.bind(this)
}
_onBackButton() {
   return true;
}

我将代码更改为:

     constructor(props){
    super(props)
    this.state = {
      transData: [],
     ...
    }
    this._onBackButton = this._onBackButton.bind(this);
  }

 _onBackButton = () => {
    return true;
 };

  componentDidMount() {
    this.handleAndroidBackButton();

    ...
  }

  componentWillUnmount () {
    this.removeAndroidBackButtonHandler();
  }

  handleAndroidBackButton = () => {
    BackHandler.addEventListener('hardwareBackPress', this._onBackButton);
  };

  removeAndroidBackButtonHandler = () => {
    BackHandler.removeEventListener('hardwareBackPress', this._onBackButton);
  }

我现在没有任何错误,但它不起作用!它不会删除其他屏幕中的事件侦听器

标签: react-native

解决方案


您拥有的 AndroidBakHandler 被命名_onBackButton ...但是您正在绑定一个名为_onBack...的方法所以只需将您的 backHandler 重命名为_onBackButton并使其成为箭头函数(自动绑定到您的类...这就是为什么您不会需要在构造函数中绑定)

// constructor() {
// No need for the next line ... arrow function is bound automatically
//        this._onBackButton = this._onBackButton.bind(this);
//  }

 _onBackButton = () => {
    return true;
 };

-

removeAndroidBackButtonHandler = () => {
  BackHandler.removeEventListener('hardwareBackPress',
                                   () => {}); // <- look at that
}

关于:“它工作正常,但是当我转到另一页时,我仍然有相同的行为。”

这是因为当您导航到另一个屏幕时(您的组件未卸载)...并且您正在删除您的 android-back-handler componentWillUnmount...

所以我建议你在导航到另一个不在的屏幕时删除你的事件监听器componentWillUnmount

还要确保在屏幕再次获得焦点时添加 android-back-handler


推荐阅读