react-native - 如何有条件地更改 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)。
我已经在 google、stackoverflow、youtube 上进行了搜索,但还没有找到满足这种需求的解决方案。
- 我正在使用反应导航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;
}
}
}
}
/>
但这给了我不正确的行为,即使它没有出错!!
如果你们不明白这个问题,请告诉我,我会让问题更具体。
如果您没有时间解释解决方案,至少给我一个代码示例或一篇文章或此用例的一些东西。
请帮助。
解决方案
您必须为此创建一个自定义标签栏并有条件地显示标签。
您可以在此处查看自定义标签栏的参考 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>
);
}
推荐阅读
- internationalization - NextJS v10 + i18n - 用不同语言重写文件夹名称
- java - 在一个类中选择的事件侦听器实体,我想将它转移到另一个类
- nginx - 仅在主页上设置基本身份验证 nginx
- apigee - 在 APIGEE 中配置多个基本路径
- javascript - ParcelJS 从 DIS 文件夹而不是 ROOT 引用文件,因此无法调试代码
- android - 使用 FlutterIcons 而不是直接使用 SVG 是否有任何性能提升?
- java - 如何在没有包装类的情况下修改 LinkedList 的头部?
- laravel - Laravel 在共享主机 net::ERR_ABORTED 404(未找到)
- python - 如何避免浮点(入)精度影响舍入
- python - 如何遍历绘图 matplotlib 的标题?