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

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

问题描述:

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

I am developing a trivia game, I am using react-navigation to handle navigation, I have 3 components, (newGame, Questions, Results ) I don't want the user to go back to the questions from the results page if the no. of questions has been exhausted, however, pressing the back button ( Android Hardware ) is taking him back to the questions. I then tried to handle the hardware back button like so:

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 页面中立即触发 NAVIGATION/BACK.这再次将其带回结果页面.

However, this is taking the user to the NewGame screen but immediately, it is bouncing back to the results page as it is firing the NAVIGATION/BACK as well immediately in the NewGame page. Which is again taking it back to the results page.

我想在登陆 NewGame 组件页面后停止后退按钮触发.有办法吗?

I want to stop the the back button to fire after I have landed in the NewGame component page. Is there a way to do it?

反应导航 = ^1.0.0-beta.11反应原生 = 0.44.0

react-navigation = ^1.0.0-beta.11 react-native = 0.44.0

您需要返回 true 表示您已经自己处理了后退按钮,正如您在 docs.

You need to return true to indicate you have handled the back button yourself as you can see in the docs.

如果一个订阅返回 true 则不会调用之前注册的订阅

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;
    });
}