android 自定义监听器 handler,React Native BackHandler不移除事件监听器

我正在使用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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值