我使用Tab.Navigator显示了4个底部导航图标,其中一个是通知图标。我想在点击tabBarBadge
选项时禁用它。如何操作?
这是我使用的代码
<Tab.Screen
name="Notifications"
component={Notifications}
options={{
tabBarIcon: ({ focused }) =>
focused ? (
<Notification_icon />
) : (
<Notification_icon_inactive />
),
tabBarBadge: 2,
}}
/>
有一种方法可以使用NavigationContainer
的ref并通过一些状态变量控制徽章的可见性。监听引用上的state
事件。在该事件的处理程序中,您可以使用ref.current?.getCurrentRoute()?.name
获取当前路由的名称。如果此名称等于Notifications
屏幕名称,则将notificationBadgeVisible
设置为false,从而隐藏徽章。检查以下代码。
const App = () => {
const ref = React.useRef<NavigationContainerRef>(null);
const [notificationBadgeVisible, setNotificationBadgeVisible] = React.useState(true);
const navigationStateChangeHandler = () => {
if (ref.current?.getCurrentRoute()?.name === 'Notifications') {
setNotificationBadgeVisible(false);
}
}
React.useEffect(() => {
ref.current?.addListener('state', navigationStateChangeHandler);
return () => { ref.current?.removeListener('state', navigationStateChangeHandler); }
});
return (
<NavigationContainer ref={ref}>
<Tab.Navigator>
<Tab.Screen name="Home" component={HomeScreen} />
<Tab.Screen
name="Notifications"
component={Notifications}
options={{
tabBarIcon: ({ focused }) =>
focused ? (
<Notification_icon />
) : (
<Notification_icon_inactive />
),
tabBarBadge: (notificationBadgeVisible ? 2 : undefined)
}}
/>
</Tab.Navigator>
</NavigationContainer>
);
};