【问题标题】:How to implement bar navigation in react native with customized buttons?如何使用自定义按钮在本机反应中实现条形导航?
【发布时间】:2021-02-19 17:22:14
【问题描述】:

您好,我是 React Native 的新手,想在这种情况下寻求帮助。 如何创建这种导航?

这不是Similar question的重复项

我不想使用CreateBottomTabNavigator,因为如您所见,导航栏位于顶部。

【问题讨论】:

  • 我现在正在尝试,无法自定义边框宽度。它需要标签的全长,但正如您从屏幕上看到的那样,我需要它约为 80%。
  • 您可以使用指示器样式更改它,让我尝试并发布答案
  • 你试过答案了吗?
  • 我明天试试,然后告诉你。非常感谢您抽出宝贵时间。

标签: javascript reactjs react-native react-navigation react-native-navigation


【解决方案1】:

您必须使用自定义标签栏来实现这一点。

您可以在此处查看自定义标签栏的代码

function MyTabBar({ state, descriptors, navigation, position }) {
  return (
    <View style={{ flexDirection: 'row', backgroundColor: 'blue' }}>
      {state.routes.map((route, index) => {
        const { options } = descriptors[route.key];
        const label =
          options.tabBarLabel !== undefined
            ? options.tabBarLabel
            : options.title !== undefined
            ? options.title
            : route.name;

        const isFocused = state.index === index;

        const onPress = () => {
          const event = navigation.emit({
            type: 'tabPress',
            target: route.key,
          });

          if (!isFocused && !event.defaultPrevented) {
            navigation.navigate(route.name);
          }
        };

        const onLongPress = () => {
          navigation.emit({
            type: 'tabLongPress',
            target: route.key,
          });
        };

        return (
          <TouchableOpacity
            accessibilityRole="button"
            accessibilityState={isFocused ? { selected: true } : {}}
            accessibilityLabel={options.tabBarAccessibilityLabel}
            testID={options.tabBarTestID}
            onPress={onPress}
            onLongPress={onLongPress}
            style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
            <Animated.Text
              style={{
                color: isFocused ? 'white' : 'grey',
                marginVertical: 10,
              }}>
              {label}
            </Animated.Text>
            <View
              style={{
                width: '80%',
                backgroundColor: isFocused ? 'white' : 'transparent',
                height: 5,
                marginTop: 'auto',
              }}></View>
          </TouchableOpacity>
        );
      })}
    </View>
  );
}

你必须像下面这样在你的导航器中使用它

<Tab.Navigator tabBar={(props) => <MyTabBar {...props} />}>

输出将是

你可以试试这个小吃 https://snack.expo.io/am8bsZI-4

您可以根据需要更改颜色、高度和边距。

其他选项是使用renderIndicator 或indicatorStyle,但它们不会正确采用宽度,因此以上将是最佳选择。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-14
    • 2012-02-17
    • 1970-01-01
    • 2023-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多