实际开发中有这么一个需求,当停留在首页的时候 点击 Android的返回键,提示再次点击退出,直接上代码
import React from "react";
import { BackHandler } from "react-native";
class ScreenWithCustomBackBehavior extends React.Component {
_didFocusSubscription;
_willBlurSubscription;
constructor(props) {
super(props);
this._didFocusSubscription = props.navigation.addListener('didFocus', payload =>
BackHandler.addEventListener('hardwareBackPress', this.onBackButtonPressAndroid)
) ;
}
componentDidMount() {
this._willBlurSubscription = this.props.navigation.addListener('willBlur', payload =>
BackHandler.removeEventListener('hardwareBackPress', this.onBackButtonPressAndroid)
);
}
onBackButtonPressAndroid = () => {
if (判断条件) {
//需要操作的事件(如:再次点击退出应用)
return true;
} else {
return false;
}
} ;
componentWillUnmount() {
this._didFocusSubscription && this._didFocusSubscription.remove();
this._willBlurSubscription && this._willBlurSubscription.remove();
}
render() {
// ...
}
}