【问题标题】:How do I disable the device back button on Android (react-native)?如何禁用 Android 上的设备后退按钮(react-native)?
【发布时间】:2019-05-14 10:59:50
【问题描述】:

如何使用 React-Native 在 Android 上禁用物理设备后退按钮?我不想为用户启用它。

【问题讨论】:

    标签: react-native-navigation wix-react-native-navigation react-native-navigation-v2


    【解决方案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 的库进行导航
        猜你喜欢
        • 1970-01-01
        • 2017-12-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-08-22
        相关资源
        最近更新 更多