我正在使用React Navigation,并且当按下后退按钮时我需要一些自定义功能。这里是我的代码:React Native BackHandler不移除事件监听器

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();

}

};

但它没有奏效。任何人都可以指出我的错误吗?

感谢

2017-09-24

Tehreem

Logo

开源鸿蒙跨平台开发社区汇聚开发者与厂商,共建“一次开发,多端部署”的开源生态,致力于降低跨端开发门槛,推动万物智联创新。

更多推荐