我试图用提示登录来覆盖屏幕上的后退按钮。见以下内容:
import React, { Component } from "react";
import { Alert, BackHandler } from "react-native";
export default class Dashboard extends Component {
constructor(props) {
super(props);
}
componentDidMount() {
BackHandler.addEventListener("hardwareBackPress",this.handleBackPress);
}
componentWillUnmount() {
BackHandler.removeEventListener("hardwareBackPress", this.handleBackPress);
}
handleBackPress() {
Alert.alert(
"Logout",
"Are you sure you want to logout?",
[
{
text: "Cancel",
onPress: () => {
console.log("Cancel Pressed");
},
style: "cancel"
},
{ text: "Logout", onPress: () => this.handleLogout() }
],
{ cancelable: false }
);
}
handleLogout() {
this.props.navigation.navigate("Login");
}
}
正如您所看到的,在安装更改时,我将将"hardwareBackPress“绑定并解除对this.handleBackPress
的绑定。注意,我必须使用.bind(this)
,否则我会
_this2.handleLogout不是一个函数
当我在警报中按下登记者时。预期的功能是:
但实际上发生的是:
我注意到我的handleBackPress()
中任何地方都没有handleBackPress()
,所以我补充说:
handleBackPress() {
Alert.alert(
"Logout",
"Are you sure you want to logout?",
[
{
text: "Cancel",
onPress: () => {
console.log("Cancel Pressed");
},
style: "cancel"
},
{
text: "Logout",
onPress: () => {
return this.handleLogout();
}
}
],
{ cancelable: false }
);
return true;
}
但现在发生的是:
我已经验证了componentDidUnmount()
是被调用的,但是它似乎并没有删除事件侦听器。
以前有人遇到过这个问题吗?目前,我只是通过在应用程序的入口添加这个处理程序来全局禁用back按钮,但这不是一个长期的解决方案。
编辑:我注意到有一个生命周期选择,所以我尝试实现它:
componentDidMount() {
this.backHandler = BackHandler.addEventListener("hardwareBackPress", () => {
Alert.alert("Logout", "Are you sure you want to logout?", [{ text: "Cancel", onPress: () => {}, style: "cancel" }, { text: "Logout", onPress: () => this.handleLogout() }], { cancelable: false });
return true;
});
}
componentWillUnmount() {
this.backHandler.remove();
}
虽然这会让它(不知何故)起作用,但它还有另一个副作用。当我向前导航(由于堆叠导航不会触发componentDidUnmount()
)并向后导航时,back按钮的行为如下:
我正往前导航的屏幕上覆盖了它的“后退”按钮,并且似乎无法很好地处理这个可选的生命周期。将尝试在所有后续屏幕上实现不同的方法;然后查看其行为是否正确。
发布于 2018-11-09 20:19:18
使用文档中的生命周期替代(https://facebook.github.io/react-native/docs/backhandler)似乎可以处理Alert和return true;
的奇怪行为
Dashboard.js
componentDidMount() {
this.backHandler = BackHandler.addEventListener("hardwareBackPress", () => {
Alert.alert("Logout", "Are you sure you want to logout?", [{ text: "Cancel", onPress: () => {}, style: "cancel" }, { text: "Logout", onPress: () => this.handleLogout() }], { cancelable: false });
return true;
});
}
componentWillUnmount() {
this.backHandler.remove();
}
handleLogout() {
global.screenName = "Dashboard";
return this.props.navigation.navigate("Login");
}
只要所有需要重写back按钮的后续屏幕也使用相同的逻辑:
Detail.js
(堆栈导航器中的后续屏幕):
componentDidMount() {
this.backHandler = BackHandler.addEventListener("hardwareBackPress", () => {
return this.props.navigation.navigate("Dashboard");
});
}
componentWillUnmount() {
this.backHandler.remove();
}
https://stackoverflow.com/questions/53232614
复制相似问题