因為文檔只列出了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.