如何制作"Go back to initial StackNavigator Screen when TabNavigator's Tab is pressed"

How to make "Go back to initial StackNavigator Screen when TabNavigator's Tab is pressed"

简介

就像 Facebook、Instagram 和任何其他移动应用程序一样,我想实施 'go back to initial screen in Stacknavigator'

  1. 如果用户按下按钮,
  2. 它回到第一页。

简单用例

  1. 查看 TabNavigator
  2. 转到 'Feed' 选项卡
  3. 转到'User'屏幕
  4. 转到另一个 'User' 屏幕
  5. 按下主选项卡图标 - 'Feed'}
  6. 返回 'Feed' 选项卡 // 这样您就不会看到 'back' 按钮

如果您不理解这个用例,请发表评论,我会为您画出它的状态流程

我的主 TabNavigator 上的图标代码。

navigationOptions: ({ navigation }) => ({
      header: null,
      tabBarIcon: ({ focused }) => {
          const { routeName } = navigation.state;
          ....
          return (
              <TochableWithoutFeedback onPress={()=>{navigation.goback(iconName)}> 
              // undefined is not a function when I press the Button 
              // deeper screen. (not getting any error on Main)
                  <Ionicons
                      name={iconName}
                      size={30}
                      style={{ marginBottom: -3 }}
                      color={focused ? Colors.tabIconSelected : Colors.tabIconDefault}
                      />
             <TochableWithoutFeedback>
         );
  },

实际上,这取决于您的路由深度,例如 Instagram 2 到 3 深度路由,其他是标签

因此您可以使用

重置路由器或返回主路由器
this.props.navigation.goBack(null)

例如。

Tab 导航子 ahs Stack 导航所以在 Stack 中,你可以做类似

// Anyone watching this, please check your react-navigation version
// I'm using ^1.0.0-beta.21.
// props for tabBarOnpress varies can be varied (Editor John Baek)
tabBarOnPress: ({scene, jumpToIndex}) => {
      jumpToIndex(scene.index)
      navigation.dispatch(NavigationActions.reset({
        index: 0,
        actions: [
          NavigationActions.navigate({ routeName: 'home' }) // go to first screen of the StackNavigator
        ]
      }))
    }

所以每当有人按下“主页”选项卡时,所有路线都会重置,您会看到 Feed 屏幕,就像 Instagram

TabNavigation 
  -Home
      |
      StakeNavigation 
                    |
                    mainScreen //main of home 
                    Subrouts 
                    RouteToProfile //just like insta

  -Search 
        |
         StakeNavigation 
                       |
                       mainScreen //main of search 
                       searchResult //if people serch some specific 

然后继续...所以在 Tab

的 stakeNavigation 级别重置路线
const SubHome = StackNavigator({
  Home: { screen: Home },
  Home2: { screen: Home2 },
  Home3 : { screen: Home3 },
},{
  navigationOptions:({navigation,screenProps})=>({
    tabBarLabel: I18n.t('tab_car'),
    tabBarIcon: ({ tintColor }) => (
      <CustomIcon name={'Home'} width={28} height={30} fill={tintColor} />
    ),
    tabBarOnPress: (tab, jumpToIndex) => {
      jumpToIndex(tab.index)
      navigation.dispatch(NavigationActions.reset({
        index: 0,
        actions: [
          NavigationActions.navigate({ routeName: 'Home' }) // go to first screen of the StackNavigator
        ]
      }))
    }
  }),
  headerMode:'none'
});