【问题标题】:Change Bottom Tab Bar based on state in React Navigation with navigationOptions使用 navigationOptions 根据 React Navigation 中的状态更改底部选项卡栏
【发布时间】:2018-09-19 19:37:40
【问题描述】:

我想根据启用的功能更改屏幕底部的选项卡。此功能列表通过登录 API 调用填充。

目前我有以下:

const TabRouteConfig = {
  Home: DashboardScreen,
  FeatureA: FeatureA,
  FeatureZ: FeatureZ,
};

const TabNavigatorConfig = {
  initialRouteName: 'Home',
  order: [
    'Home',
    'Feature A',
  ],
  tabBarPosition: 'bottom',
  lazy: true,
};

const TabNavigator1 = createBottomTabNavigator(
  TabRouteConfig,
  TabNavigatorConfig,
);

// Set the tab header title from selected route
// https://reactnavigation.org/docs/en/navigation-options-resolution.html#a-stack-contains-a-tab-navigator-and-you-want-to-set-the-title-on-the-stack-header
TabNavigator1.navigationOptions = ({ navigation }) => {
  const { index, routes } = navigation.state;
  const { routeName } = routes[index];

  return {
    headerTitle: routeName,
  };
};

const TabNavigator2 = createBottomTabNavigator(
  TabRouteConfig,
  {
   ...TabNavigatorConfig,
   order: [
      'Home',
      'Feature Z',
   ]

);

TabNavigator2.navigationOptions = TabNavigator1.navigationOptions;

const Stack = createStackNavigator({
  Main: {
    screen: props => (props.screenProps.hasFeature ?
      <TabNavigator1 /> : <TabNavigator2 />
    )
  },
})

const WrappedStack = props => (
  <View style={styles.container}>
    <Stack
      screenProps={{ hasFeature: props.hasFeature }}
    />
  </View>
);

const mapStateToProps = (state, props) => {
  return {
    ...props,
    hasFeature: state.hasFeature,
  };
};

export default connect(mapStateToProps, null)(WrappedStack);

这主要是有效的 - 它基于hasFeatureTabNavigator1TabNavigator2 之间动态切换,但它不再支持放置在 TabNavigators 上的navigationOptions 并且未设置headerTitle

有没有更好的方法来做到这一点?

【问题讨论】:

  • WrappedStack 是否具有导航属性,即 props.navigation

标签: react-native react-navigation


【解决方案1】:

同时渲染多个导航器是一种反模式,因为这些导航器的导航状态将完全分离,您将无法导航到另一个导航器。

您可以使用tabBarComponent 选项来实现您想要的。希望你能从下面的例子中得到想法:

import { createBottomTabNavigator, BottomTabBar } from 'react-navigation-tabs';

const TabNavigator = createBottomTabNavigator(
  TabRouteConfig,
  {
    tabBarComponent: ({ navigation, ...rest }) => {
      const filteredTabNavigatorRoutes = navigation.state.routes.filter(route => isRouteAllowed(route));
      return (
        <BottomTabBar
          {...rest}
          navigation={{
            ...navigation,
            state: { ...navigation.state, routes: filteredTabNavigatorRoutes },
          }}
        />
      );
    },
  },
);

注意事项:

  • 您不必单独安装react-navigation-tabs。它与react-navigation 2.0.0+ 一起自动安装。
  • isRouteAllowed 是根据是否显示该路线返回truefalse 的函数。确保只检查该对象中的顶级路由。
  • TabRouteConfig 应该包含所有可能的选项卡,并且此逻辑仅在视觉上隐藏 TabBar 中的路由。因此,您仍然可以以编程方式导航到所有路线。因此,您可能需要在每个屏幕中添加额外的逻辑来决定是否根据hasFeature 呈现它们。

【讨论】:

    猜你喜欢
    • 2023-04-07
    • 1970-01-01
    • 2022-11-04
    • 2023-03-26
    • 2020-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-04
    相关资源
    最近更新 更多