【发布时间】:2017-09-24 16:14:26
【问题描述】:
我正在使用 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();
}
};
但它没有用。谁能指出我的错误?
谢谢
【问题讨论】:
标签: android react-native react-navigation