實際開發(fā)中有這么一個需求闻葵,當停留在首頁的時候 點擊 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() {
// ...
}
}
最后編輯于 :
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者