【发布时间】:2019-05-14 10:59:50
【问题描述】:
如何使用 React-Native 在 Android 上禁用物理设备后退按钮?我不想为用户启用它。
【问题讨论】:
标签: react-native-navigation wix-react-native-navigation react-native-navigation-v2
如何使用 React-Native 在 Android 上禁用物理设备后退按钮?我不想为用户启用它。
【问题讨论】:
标签: react-native-navigation wix-react-native-navigation react-native-navigation-v2
在 app.js 中使用启动应用程序时创建的侦听器来跟踪当前打开的屏幕。应用主组件创建一个BackHandler监听器,根据当前打开的屏幕响应设备返回按钮。
主要组件:
componentDidMount() {
BackHandler.addEventListener('hardwareBackPress', this.onBackPress);
}
componentWillUnmount() {
BackHandler.removeEventListener('hardwareBackPress', this.onBackPress);
}
onBackPress = () => {
if (this.props.currentScreen.name === 'app.main') {
Alert.alert(
'Confirm exit',
'Do you want to exit App?',
[
{text: 'CANCEL', style: 'cancel'},
{text: 'OK', onPress: () => {
BackHandler.exitApp()
}
}
]
);
} else {
Navigation.pop(this.props.currentScreen.id);
}
return true;
}
App.js
//register to compomentDidApperaListener to keep track on which screen is currently open. The componentName and Id are stored in my redux store
Navigation.events().registerComponentDidAppearListener(({ componentId, componentName }) => {
store.dispatch(updateCurrentScreen({'name': componentName, 'id': componentId}))
})
【讨论】:
从今天开始,React Native Navigation 在 v2 上没有开箱即用的支持。但是,您可以使用来自 React native 本身的 BackHandler。处理它并返回 false 以禁用它。
BackHandler 上的文档
BackHandler.addEventListener('hardwareBackPress', function() {
return false;
});
【讨论】:
在活动中,您可以覆盖onBackPressed() 并注释对超类的调用。
@Override
public void onBackPressed() {
// super.onBackPressed(); comment this line to disable back button press
}
【讨论】: