关于如何实现react-navigation的动态tab,react-navigation的官库上大概有100多个issuse是关于这个的https://github.com/react-navigation/react-navigation/issues?utf8=%E2%9C%93&q=dynamic+tab
但上面的方案都不尽人意,接下来说下我的方案哈:
要实现动态Tab的功能,我们可以实现一个DynamicTabNavigator:
import {BottomTabBar, createBottomTabNavigator} from 'react-navigation-tabs';
const TABS = {//在这里配置页面的路由
Page1: {
screen: Page1,
navigationOptions: {
tabBarLabel: 'Page10',
tabBarIcon: ({tintColor, focused}) => (
<Ionicons
name={focused ? 'ios-home' : 'ios-home-outline'}
size={26}
style={{color: tintColor}}
/>
),
}
},
Page2: {
screen: Page2,
navigationOptions: {
tabBarLabel: 'Page2',
tabBarIcon: ({tintColor, focused}) => (
<Ionicons
name={focused ? 'ios-people' : 'ios-people-outline'}
size={26}
style={{color: tintColor}}
/>
),
}
},
Page3: {
screen: Page3,
navigationOptions: {
tabBarLabel: 'Page3',
tabBarIcon: ({tintColor, focused}) => (
<Ionicons
name={focused ? 'ios-chatboxes' : 'ios-chatboxes-outline'}
size={26}
style={{color: tintColor}}
/>
),
}
},
};
export default class DynamicTabNavigator extends React.Component {
constructor(props) {
super(props);
console.disableYellowBox = true;
}
/**
* 获取动态的Tab
* @returns {*}
* @private
*/
_tabNavigator() {
let tabs = {};
if (this.props.navigation.state.params.tabs) {
/**
* 取出上一个页面传过来的要显示的tab参数,也可以是从服务端下发的的Tab的配置,
* 比如显示createBottomTabNavigator中的那些Tab,
* 这个配置页可以是在其他页面获取之后通过AsyncStorage写入到本地缓存,
* 然后在这里读取缓存,也可以通过其他方式如props、global config等获取
***/
this.props.navigation.state.params.tabs.forEach(e => {//根据需要定制要显示的tab
tabs[e] = TABS[e];
})
} else {
const {Page1, Page2} = TABS;//根据需要定制要显示的tab
tabs = {Page1, Page2};
Page1.navigationOptions.tabBarLabel = 'P1';//动态修改Tab的属性
}
return createBottomTabNavigator(tabs, {//应用修改后的tab
tabBarComponent: TabBarComponent,
tabBarOptions: {
activeTintColor: Platform.OS === 'ios' ? '#e91e63' : '#fff',
}
});
}
render() {
const Tabs = this._tabNavigator();
return (
<Tabs/>
);
}
}
class TabBarComponent extends React.Component {
constructor(props) {
super(props);
this.theme = {
tintColor: props.activeTintColor,
updateTime: new Date().getTime()
}
}
render() {
const {routes, index} = this.props.navigation.state;
if (routes[index].params) {
const {theme} = routes[index].params;
if (theme && theme.updateTime > this.theme.updateTime) {
this.theme = theme;
}
}
/**
* custom tabBarComponent
* https://github.com/react-navigation/react-navigation/issues/4297
*/
return (
<BottomTabBar
{...this.props}
activeTintColor={this.theme.tintColor || this.props.activeTintColor}
/>
);
}
}
然后,在createStackNavigator中使用这个DynamicTabNavigator:
export const AppStackNavigator = createStackNavigator({
HomePage: {
screen: HomePage
},
...
TabNav: {
screen: DynamicTabNavigator,
navigationOptions: {//在这里定义每个页面的导航属性,静态配置
title: "This is TabNavigator.",
}
}
}, {
navigationOptions: {
// header: null,// 可以通过将header设为null 来禁用StackNavigator的Navigation Bar
}
});