遇到问题:
项目中用到的路由组件是react-navigation,当使用常规方法(监听backHandleer进行操作)时,所有页面都会监听返回按钮,并且this.props.navigation的值为该段代码所在的页面,因此无法得到点击返回按钮时的当前页面,即无法实现特定页面退出程序和另外页面返回上级的功能。
解决方案:
使用react-native-back-android组件。
具体使用方法:
在TabNavigator定义页面:
mport backAndroid, {
hardwareBackPress,
exitApp
} from 'react-native-back-android';
const FescoZP = StackNavigator(
{
//Filter:{screen:FilterScreen},
Login: {screen: hardwareBackPress(LoginScreen)},
Authen:{screen: AuthenScreen},
MainScreen:{screen: MainScreenNavigator},
//Filter: { screen: FilterScreen},
Filter: { screen: hardwareBackPress(FilterScreenBK)},
Map: {screen: hardwareBackPress(MapScreen)},
SetUp: {screen: hardwareBackPress(SetUpScreen)}
}
),
AppRegistry.registerComponent('FescoZP', () => backAndroid(FescoZP));
其中,在路由栈中,在最顶层的页面(本例为“login”)中实现handleHardwareBackPress方法,则在剩下其他页面都可以监听到该方法,如果想在其他页面阻止该方法的实现,只能重新实现handleHardwareBackPress。
在本例中:LoginScreen.js 片段:
handleHardwareBackPress = () => {
Alert.alert(
'Quiting',
'Want to quit?',
[
{
text: 'Cancel',
onPress: () => console.log('Cancel Pressed'),
style: 'cancel'
},
{ text: 'OK', onPress: () => exitApp() }
],
{ cancelable: false }
);
// return true to stop bubbling
return true
};
FilterScreen.js 代码片段:
handleHardwareBackPress = () => {
const { goBack } = this.props.navigation
console.warn('6666');
goBack();
// return true to stop bubbling
return true
};