我正在使用React Navigation,按下后退按钮时我需要一些自定义功能。这是我的代码:
class AddEditIngredient extends Component {
constructor(props) {
super(props);
this.state = {
editStarted: false
};
this.goBack = () => {
if (this.state.editStarted === true) {
Alert.alert(
"Ingredient Not Saved",
"Do you want to navigate away without saving ingredient?",
[
{ text: "Cancel", onPress: () => null, style: "cancel" },
{ text: "Yes", onPress: () => this.props.navigation.goBack() }
],
{ cancelable: true }
);
} else {
this.props.navigation.goBack();
}
};
}
componentWillMount() {
BackHandler.addEventListener("hardwareBackPress", this.goBack);
}
componentWillUnmount() {
BackHandler.removeEventListener("hardwareBackPress", this.goBack);
}
我的goBack功能适用于屏幕上的后退按钮,但是当我尝试按下物理后退按钮时,它会弹出所有屏幕并最小化应用程序。通过阅读以前关于该问题的帖子我收集的内容,removeEventListener并不是指与addEventListener相同的函数。所以我尝试了这个:
constructor(props) {
super(props);
this.state = {
editStarted: false
};
this.goBack = this.goBack.bind(this);
}
goBack = () => {
if (this.state.editStarted === true) {
Alert.alert(
"Ingredient Not Saved",
"Do you want to navigate away without saving ingredient?",
[
{ text: "Cancel", onPress: () => null, style: "cancel" },
{ text: "Yes", onPress: () => this.props.navigation.goBack() }
],
{ cancelable: true }
);
} else {
this.props.navigation.goBack();
}
};
但它没有用。谁能指出我的错误?
由于
答案 0 :(得分:0)
最后在this post找到答案。我需要在goBack函数结束时返回true,以指示已经处理了后退行为。
答案 1 :(得分:0)
您需要在自定义后向监听器上附加return true
或return false
才能跟随父处理程序