Resetting the navigation stack when changing tab (StackNavigators nested in TabNavigator)

梦想的初衷 提交于 2019-12-24 08:07:18

问题


I have two StackNavigator. Movies:

const MoviesStackNavigator = createStackNavigator({
  Movies: Movies,
  MovieDetails: MovieDetails,
},{
  initialRouteName: 'Movies',
})

and actors:

const ActorsStackNavigator = createStackNavigator({
  Actors: Actors,
  ActorDetails: ActorDetails,
},{
  initialRouteName: 'Actors',
})

I am using them inside a TabNavigator:

const RootTabs = createBottomTabNavigator({
  Movies: {
    screen: MoviesStackNavigator,
    navigationOptions: {
      tabBarLabel: 'Movies'
    }
  },
  Actors: {
    screen: ActorsStackNavigator,
    navigationOptions: {
      tabBarLabel: 'Actors'
    }
  },
})

When the user changes tab, I want him to arrive to the root component of that tab (Movies or Actors), not to a stacked component (MoviesDetails or ActorsDetails). In other word, when a user quits a tab, the StackNavigator in that tab should be resetted to the root component.

My first approach was to use StackActions.reset when initializing the root component in a tab to try to reset the other tab (that the user just quit) but the library prevents interacting between navigators, at least in that way.

So, any ideas?


回答1:


My solution was to use tabBarOnPress:

const RootTabs = createBottomTabNavigator({
  Movies: {
    screen: MoviesStackNavigator,
    navigationOptions: {
      tabBarLabel: 'Movies',
      tabBarOnPress: ({navigation, defaultHandler}: any) => {
        navigation.navigate('Actors')
        defaultHandler()
      },
    }
  },
  Actors: {
    screen: ActorsStackNavigator,
    navigationOptions: {
      tabBarLabel: 'Actors',
      tabBarOnPress: ({navigation, defaultHandler}: any) => {
        navigation.navigate('Movies')
        defaultHandler()
      },
    }
  },
})


来源:https://stackoverflow.com/questions/51991396/resetting-the-navigation-stack-when-changing-tab-stacknavigators-nested-in-tabn

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!