【发布时间】:2022-08-18 20:12:29
【问题描述】:
在 React Native 底部选项卡导航中,如何创建自己的自定义 btn,在按下时在当前屏幕中执行操作而不在其他屏幕中导航?
*我知道如何创建自定义 btn
标签: react-native
在 React Native 底部选项卡导航中,如何创建自己的自定义 btn,在按下时在当前屏幕中执行操作而不在其他屏幕中导航?
*我知道如何创建自定义 btn
标签: react-native
如果您想为底部导航栏中的所有按钮实现自定义按钮并仅为一个按钮添加自定义操作,那么最简单的方法是 implement a custom tabBar 并为路由添加条件。
这是一个关于如何工作的最小示例。
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
const Tab = createBottomTabNavigator();
export default function App() {
return (
<NavigationContainer>
<Tab.Navigator tabBar={props => <CustomTabBar {...props} />}>
<Tab.Screen name="Settings" component={SettingsScreen} />
<Tab.Screen name="Home" component={HomeScreen} />
<Tab.Screen name="CustomAction" />
</Tab.Navigator>
</NavigationContainer>
);
}
这是CustomTabBar 的实现。
function CustomTabBar({ state, descriptors, navigation }) {
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;
const onPress = () => {
const event = navigation.emit({
type: 'tabPress',
target: route.key,
canPreventDefault: true,
});
console.log(route)
if (route.name === "CustomAction") {
console.log("Hello World")
} else if (!isFocused && !event.defaultPrevented) {
navigation.navigate({ name: route.name, merge: true });
}
};
const onLongPress = () => {
navigation.emit({
type: 'tabLongPress',
target: route.key,
});
};
return (
<TouchableOpacity
onPress={onPress}
onLongPress={onLongPress}
style={{ flex: 1 }}
>
<Text style={{ color: isFocused ? '#673ab7' : '#222' }}>
{label}
</Text>
</TouchableOpacity>
);
})}
</View>
);
}
我已经修改了文档中提供的示例。关键部分如下
if (route.name === "CustomAction") {
console.log("Hello World")
} else if (!isFocused && !event.defaultPrevented) {
navigation.navigate({ name: route.name, merge: true });
}
以及以下
<Tab.Screen name="CustomAction" />
我添加了一个名为CustomAction 的虚拟屏幕,但没有提供组件。在onPress 函数中,如果按下此选项卡,我将添加一个自定义操作。
【讨论】: