如何禁用 Android 上的设备后退按钮(react-native)?
Posted
技术标签:
【中文标题】如何禁用 Android 上的设备后退按钮(react-native)?【英文标题】:How do I disable the device back button on Android (react-native)? 【发布时间】:2019-05-14 10:59:50 【问题描述】:如何使用 React-Native 在 android 上禁用物理设备后退按钮?我不想为用户启用它。
【问题讨论】:
【参考方案1】:在 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))
)
【讨论】:
【参考方案2】:从今天开始,React Native Navigation 在 v2 上没有开箱即用的支持。但是,您可以使用来自 React native 本身的 BackHandler
。处理它并返回 false 以禁用它。
BackHandler 上的文档
示例
BackHandler.addEventListener('hardwareBackPress', function()
return false;
);
【讨论】:
【参考方案3】:在活动中,您可以覆盖onBackPressed()
并注释对超类的调用。
@Override
public void onBackPressed()
// super.onBackPressed(); comment this line to disable back button press
【讨论】:
抱歉,好像我没有明确说明这是针对 react-native 的,我正在使用一个名为 react-native-navigation 的库进行导航以上是关于如何禁用 Android 上的设备后退按钮(react-native)?的主要内容,如果未能解决你的问题,请参考以下文章
如何在一个页面上禁用 Android 后退按钮并在所有其他页面上更改为退出按钮
如何在 React Native 中的启动画面后禁用后退按钮