[react native] react-native-tab-navigator在子Component中隐藏

因为文档只列出了TabBarIOS, 不支持Android,所以github上找到这个组件。

先说下我的页面构造: 入口文件 —> 注册组件(包含Navigator, 跳转到欢迎页)—> 欢迎页(一定时间后replace navigator) —> 底部导航页面

底部导航引用TabNavigator插件react-native-tab-navigator(TabNavigator创建子Component的写法是参考github上一个开源项目

1 <TabNavigator
2      hidesTabTouch={false}
3      sceneStyle={{paddingBottom: 0}}
4      tabBarStyle={tabBarShow ? styles.tabNav : styles.tabNavHide}>
5           {this._renderTabItem(HOME_NORMAL, HOME_PRESS, HOME_TAB, '首页', 0, this._createChildView(HOME_TAB))}
6           {this._renderTabItem(MESSAGE_NORMAL, MESSAGE_PRESS, SHOP_TAB, '商家', 1, this._createChildView(SHOP_TAB))}
7           {this._renderTabItem(ME_NORMAL, ME_PRESS, ME_TAB, '我的', 0, this._createChildView(ME_TAB))}
8           {this._renderTabItem(DISCOVER_NORMAL, DISCOVER_PRESS, MORE_TAB, '更多', 0, this._createChildView(MORE_TAB))}
9 </TabNavigator>

在renderTabItem中,传入导航项目相关参数—图片(img)、选中图片(selectedImg)、标签(tag)、题目(title)、提示数目(badge)、子视图(childView);

 1 _renderTabItem(img, selectedImg, tag, title, badgeCount, childView) {
 2     return (
 3         <TabNavigator.Item
 4             selected={this.state.selectedTab===tag}
 5             renderIcon={()=><Image style={styles.tabIcon} source={img}/>}
 6             title={title}
 7             selectedTitleStyle={styles.selectedTitleStyle}
 8             renderBadge={()=>this._renderBadge(badgeCount)}
 9             renderSelectedIcon={()=><Image style={styles.tabIcon} source={selectedImg}/>}
10             onPress={()=>this.setState({selectedTab:tag})}>
11             {childView}
12         </TabNavigator.Item>
13     );
14 }

底部导航图片的切换,通过onPress方法改变state. {childView} 来自 childView, 也就是_createChildView(tag)

在这里,只需要把引入的子视图中传入注册App时的navigator, 然后在navigator中push component ,就可以做到在子视图中隐藏底部导航

 1 _createChildView(tag) {
 2     let renderView;
 3     switch (tag) {
 4         case HOME_TAB:
 5             renderView = <HomePage {...this.props} />;
 6             break;
 7         case SHOP_TAB:
 8             renderView = <ShopPage />;
 9             break;
10         case ME_TAB:
11             renderView = <MePage />;
12             break;
13         case MORE_TAB:
14             renderView = <MorePage />;
15             break;
16         default:
17             break;
18     }
19     return (<View style={styles.container}>{renderView}</View>)
20 }

大概说下原理(我的理解):

注册页的navigator包含了TabNavigator, TabNavigator中包含了childView。

如果在childView中使用新的Navigator push component,那么这个component也属于TabNavigator, 所以这种方式创建的新界面还会包含底部导航。

所以要通过注册页的navigator来push component.