首页 > 解决方案 > 在 react-navigation 的 createMaterialTopTabNavigator 上制作动态选项卡

问题描述

我正在使用 react-navigation 的 createMaterialTopTabNavigator 制作顶部选项卡导航器。我面临的问题是选项卡必须由 API 请求的响应数据决定。例如,我调用一个 API 来请求足球队列表,接收列表,然后设置MaterialTopTabNvigator.

我已经使用如下组件制作了导航器的标签:

class TabBarLabel extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return this.props.focused ? (
      <View style={lstyles.container_focused}>
        <Text style={lstyles.label_focused}>{this.props.name}</Text>
      </View>
    ) : (
      <View style={lstyles.container_blur}>
        <Text style={lstyles.label_blur}>{this.props.name}</Text>
      </View>
    );
  }
}

const FootballTeamNavigator = createMaterialTopTabNavigator(
  {
    teamA : {
      screen: AScreenComponent,
      navigationOptions: () => {
        return {
          title: 'teamA',
          tabBarLabel({focused}) {
            return <TabBarLabel focused={focused} name="teamA" />;
          }
        };
      }
    }
  },
  {
    initialRouteName: teamA,
    swipeEnabled: false,
    timingConfig: {
      duration: 1000,
    },
    tabBarOptions: {
      scrollEnabled: true,
      ...styles,
    },
  },
);

我想做的是:

let teamList = {};

apiForGetFootballTeamList().then(response => {
  for (const team of response.data.list) {
    tempList[team.name] = team;
  }
});

createMaterialTopTabNavigator(
  {
    ...teamList
  },
  {
    initialRouteName: ...,
    ...
  }
);

但我不知道如何使用组件等数据更新选项卡。(组件有状态,如果我们更新状态,组件就会更新)

有什么办法吗?

标签: react-nativereact-navigation

解决方案


当前版本的 React Navigation 不支持动态配置。您需要为此使用 React 导航 5 https://blog.expo.io/announcing-react-navigation-5-0-bd9e5d45569e


推荐阅读