1

在我的移动应用程序中,我有一个带有标签导航的屏幕。在第一个选项卡中,我想添加一个返回处理程序以退出应用程序。但在其他选项卡中,我不希望这种情况发生。我实现了这个,如下所示。

constructor(props) {
  super(props);

  this.handleBackButtonClick = this.handleBackButtonClick.bind(this);
  this.state = {};
}

componentWillMount() {
  BackHandler.addEventListener('hardwareBackPress', this.handleBackButtonClick);
}

componentWillUnmount() {
  BackHandler.removeEventListener('hardwareBackPress', this.handleBackButtonClick);
}

handleBackButtonClick() {
  BackHandler.exitApp();
  return true;
}

此功能在第一个选项卡中运行良好。但我的问题是,在其他选项卡中,当我单击后退按钮时,应用程序退出。我希望这些选项卡中有不同的功能。根据我的研究,标签导航不会调用 componentWillUnmount。因此,它不会删除选项卡导航上的事件侦听器。但我找不到其他解决方案。

如果有任何解决方案可以仅在第一个选项卡中实现退出应用程序功能,我将不胜感激。

4

1 回答 1

1

您可以设置一个状态并在 handleBackButton 中检查它。例如,如果您使用的是 react-navigation,您可以添加如下内容:

<Tab.Navigator
    screenOptions={({ route }) => ({
        if (route.name === 'First tab') {
             this.setState({canExit: true});
        }
        else {
            this.setState({canExit: false});
        }
    })}
/>

然后您可以像这样更改处理程序:

handleBackButtonClick() {
    if(this.state.canExit){
       BackHandler.exitApp();
    }
    return true;
}
于 2020-02-24T09:37:49.600 回答