React Navigation V5使用自定义bottomTab组件时不接收聚焦参数

问题描述 投票:1回答:1

我目前正在尝试在我的本机应用程序中实现自定义tabBar设计,该应用程序使用React Navigation 5作为导航库。一切工作正常,除了我的tabBarIcons没有收到任何道具,所以我无法确定我是否必须显示活动或不活动的tabIcon。每当我使用默认选项卡时,我都会收到道具,因此自定义选项卡中肯定有问题。我确实遵循了文档,但仅找到发出'tabPress'事件的指令。但是我确实认为我应该发出更多事件来获得正确的重点道具。我已经这样设置了导航器:

const Tabs = createBottomTabNavigator();

export default () => (
  <Tabs.Navigator tabBar={TabBarComponent} initialRouteName="Home">
    <Tabs.Screen
      name="Home"
      component={HomeScreen}
      options={{
        tabBarIcon: ({ focused }) => {
          // The props here are {}, so focused is undefined.
          const icon = focused
            ? require('images/iconOverviewRed.png')
            : require('images/iconOverviewGrey.png');

          return <Image source={icon} />;
        },
      }}
    />
    <Tabs.Screen
      name="Overview"
      component={OverviewScreen}
      options={{
        tabBarIcon: props => {
          console.log(props);
          return <Image source={require('images/logoRed.png')} />;
        },
      }}
    />
    <Tabs.Screen
      name="Account"
      component={AccountScreen}
      options={{
        tabBarIcon: ({ focused }) => {
          const icon = focused
            ? require('images/iconAccountRed.png')
            : require('images/iconAccountGrey.png');

          return <Image source={icon} resizeMethod="resize" />;
        },
      }}
    />
  </Tabs.Navigator>
);

这是我的自定义tabBar组件:

const TabBar = ({ navigation, state, descriptors }: any) => {
  return (
    <View style={styles.container}>
      {state.routes.map((route: any) => {
        const onPress = () => {
          const event = navigation.emit({
            type: 'tabPress',
            target: route.key,
            canPreventDefault: true,
          });

          if (!event.defaultPrevented) {
            navigation.dispatch({
              ...TabActions.jumpTo(route.name),
              target: state.key,
            });
          }
        };

        return (
          <TabIcon
            key={route.key}
            Icon={descriptors[route.key].options.tabBarIcon}
            onPress={onPress}
            isBig={route.name === 'Home'}
          />
        );
      })}
    </View>
  );
};

const TabIcon = ({ onPress, Icon, key, isBig }: any) => {
  return (
    <TouchableWithoutFeedback key={key} onPress={onPress}>
      <View style={isBig ? styles.bigTab : styles.defaultTab} key={key}>
        <Icon />
      </View>
    </TouchableWithoutFeedback>
  );
};

提前感谢。

react-native react-navigation react-navigation-v5 react-navigation-bottom-tab
1个回答
0
投票

descriptors[route.key].options只是为您提供了已指定的选项。如果记录descriptors[route.key].options.tabBarIcon的值,您会看到它会打印您指定的功能。

在您的自定义标签栏中,您可以根据需要使用该选项。由于这里是函数,因此您必须调用它并传递所需的参数。

descriptors[route.key].options.tabBarIcon({ focused: state.index === index })

这也意味着您可以完全控制该选项。您可以直接输入所需的任何类型,函数,require语句等,然后使用它。您也不必将其命名为tabBarIcon,您可以根据需要将其命名。

© www.soinside.com 2019 - 2024. All rights reserved.