react-native - 无法删除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);
}
我现在没有任何错误,但它不起作用!它不会删除其他屏幕中的事件侦听器
解决方案
您拥有的 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
推荐阅读
- angular - 如何用角度解决数据绑定错误
- r - 如何从假变为真
- laravel - Laravel - HTTP 客户端返回 403
- reactjs - 在 React 中从状态对象构建的表格行上显示两个按钮?
- apache - 在 localhost 上更改 Apache 侦听
- jasmine - 无法使用 Jasmine(量角器)定位元素
- javascript - 将来自 axios GET 调用的响应保存到 Firebase 函数的 JavaScript 部分中的 Firebase 数据库
- regex - 固定长度字符串的正则表达式,从数字 0 开始
- python - 从 GCP 云函数写入 GCP 数据存储区重定向到不需要的登录提示
- arrays - 使用 Google 表格过滤两列