javascript - 如何阻止 Android 硬件后退按钮在 react-native 的 react-navigation 中运行?

标签 javascript react-redux react-native react-navigation

我正在开发一个问答游戏,我正在使用 react-navigation 来处理导航,我有 3 个组件,(newGame、Questions、Results)我不希望用户返回到结果页面的问题,如果没有。问题已经用完,但是,按下后退按钮(Android 硬件)会将他带回问题。然后我尝试像这样处理硬件后退按钮:

componentWillMount() {
      this.props.gameState(true);
      BackHandler.addEventListener('hardwareBackPress', () => {
        if (this.props.gamePlaying) { // Currently set to true. I will set it to false again on NewGame Page.
          this.props.navigation.navigate('NewGame');
        }
      });
    }

但是,这会将用户带到 NewGame 屏幕,但会立即弹回结果页面,因为它会立即在 NewGame 页面中触发导航/返回。这再次将其带回结果页面。

可能的修复方法?

我想在进入 NewGame 组件页面后停止触发后退按钮。有办法吗?

我的环境

react 导航 = ^1.0.0-beta.11 react native = 0.44.0

最佳答案

您需要返回 true 以指示您自己处理了后退按钮,如您在 docs 中所见.

if one subscription returns true then subscriptions registered earlier will not be called

您的代码应如下所示:

componentWillMount() {
    this.props.gameState(true);
    BackHandler.addEventListener('hardwareBackPress', () => {
        if (this.props.gamePlaying) {
            this.props.navigation.navigate('NewGame');
            return true; // This will prevent the regular handling of the back button
        }

        return false;
    });
}

关于javascript - 如何阻止 Android 硬件后退按钮在 react-native 的 react-navigation 中运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44774375/

相关文章:

javascript - 将 react 组件绑定(bind)到部分 redux 状态

javascript - 使用react-redux时,prevProps和this.props将始终在componentDidUpdate中返回相同的值

unit-testing - Jest – 如何模拟模块中的非默认导出?

Android react-native-push-notification onNotification 当应用程序在后台并单击通知时未调用?

javascript - Supabase onAuthStateChanged - 如何正确等待请求完成以防止使用 useEffect 闪烁?

javascript - FusionCharts 无法在 Google Chrome 和 Firefox 中呈现

javascript - 在 v-for 迭代之间包含一次元素

reactjs - 关于乐观更新 : when do we need it? 的后续问题

javascript - 使用 Webstorm 9.0 进行实时编辑

javascript - 传单中圆圈内的照片标记