如何有条件地更改React Native底部选项卡中的屏幕按钮



我有一个底部选项卡,上面有按钮a、B、C、D、E。

  • 当我在屏幕上时A我希望选项卡显示B、C、D、E按钮,但不显示按钮A
  • 当我在屏幕上B时,我希望选项卡显示A、C、D、E按钮,但不显示按钮B
  • 当我在其他屏幕上时,我想显示A、C、D、E按钮或B、C、D、E(取决于我选择A还是B(

我在谷歌、stackoverflow、youtube上搜索过,但还没有找到解决这一需求的方案。

  • 我使用的是react导航v5

我已经尝试了很多方法,像这样的东西:

<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;
}
}     
}
}
/>

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

如果你们不理解这个问题,请告诉我,我会让问题变得更加具体。

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

PLZ帮助

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

您可以在此处查看自定义选项卡栏的参考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/@gurupan/customtab

建议为底部导航开发一个共享的通用组件(使用不同的参数来控制按钮的数量和位置(。你把底部的导航放在每一页。

在这种情况下,每个页面都有其自定义的导航底部显示。

最新更新