首页 > 解决方案 > 如何有条件地更改 React Native 底部选项卡中的屏幕按钮?

问题描述

我有一个带有按钮 A、B、C、D、E 的底部选项卡。

我已经在 google、stackoverflow、youtube 上进行了搜索,但还没有找到满足这种需求的解决方案。

我已经尝试了很多方法和类似的东西:

<Tab.Screen name="A" component={A}
   options={
     ()=>{
       tabBarButton:(props)=>{
         if(isScreen("A")){
            return null;
         }else{
            return <TouchableOpacity {...props}/>
         }
       }     
     }
   }
/>

<Tab.Screen name="B" component={B}
   options={
     ()=>{
       tabBarButton:(props)=>{
         if(isScreen("A")){
            return <TouchableOpacity {...props}/>
         }else{
            return null;
         }
       }     
     }
   }
/>

但这给了我不正确的行为,即使它没有出错!!

如果你们不明白这个问题,请告诉我,我会让问题更具体。

如果您没有时间解释解决方案,至少给我一个代码示例或一篇文章或此用例的一些东西。

请帮助。

标签: react-nativereact-navigationreact-native-navigationreact-navigation-v5react-navigation-bottom-tab

解决方案


您必须为此创建一个自定义标签栏并有条件地显示标签。

您可以在此处查看自定义标签栏的参考 https://reactnavigation.org/docs/bottom-tab-navigator/#tabbar

您将必须创建如下所示的内容(我已经修改了文档中的示例代码)

function MyTabBar({ state, descriptors, navigation }) {

  //Condition to decide the tab or not
  const shouldDisplay = (label, isFocused) => {
    if (label === 'A' && isFocused) return false;
    else if (label === 'B' && isFocused) return false;
    else return true;
  };

  return (
    <View style={{ flexDirection: 'row' }}>
      {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;

        if (!shouldDisplay(label, isFocused)) return null;

        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 }}>
            <Text style={{ color: isFocused ? '#673ab7' : '#222' }}>
              {label}
            </Text>
          </TouchableOpacity>
        );
      })}
    </View>
  );
}

您可以在下面的小吃 https://snack.expo.io/@guruparan/customtabs中看到代码


推荐阅读