我已经在我的主屏幕上的反应本机应用程序中放置了 android 后退按钮退出应用程序功能。但是当我在其他屏幕上按下 android 后退按钮时,它也会被调用。
componentDidMount() {
if (Platform.OS == "android") {
BackHandler.addEventListener('hardwareBackPress', this.handleBackButton);
}
this._setupGoogleSignin();
this._getUserDetails();
const { navigate } = this.props.navigation;
console.log("object url is", this.state.postsArray[0].url);
}
handleBackButton = () => {
Alert.alert(
'Exit App',
'Exiting the application?', [{
text: 'Cancel',
onPress: () => console.log('Cancel Pressed'),
style: 'cancel'
}, {
text: 'OK',
onPress: () => BackHandler.exitApp()
}, ], {
cancelable: false
}
)
return true;
}
componentWillUnmount() {
BackHandler.removeEventListener('hardwareBackPress', this.handleBackButton);
}
原文由 Paras Watts 发布,翻译遵循 CC BY-SA 4.0 许可协议
如果当您导航到其他屏幕或卸载
HomeScreen
时您的 HomeScreen 仍然安装,如果您不删除 EventListener,它仍会被调用。您应该在导航或卸载时清除 EventListener,