| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091 |
- import React, { ReactNode } from 'react'
- import { View } from '@tarojs/components'
- import { TabBar, TabBarItem } from '@/components/ui/tab-bar'
- import Taro from '@tarojs/taro'
- import { useCart } from '@/contexts/CartContext'
- export interface TabBarLayoutProps {
- children: ReactNode
- activeKey: string
- }
- const tabBarItems: TabBarItem[] = [
- {
- key: 'home',
- title: '首页',
- iconClass: 'i-heroicons-home-20-solid',
- selectedIconClass: 'i-heroicons-home-20-solid',
- },
- {
- key: 'category',
- title: '分类',
- iconClass: 'i-heroicons-squares-2x2-20-solid',
- selectedIconClass: 'i-heroicons-squares-2x2-20-solid',
- },
- {
- key: 'cart',
- title: '购物车',
- iconClass: 'i-heroicons-shopping-cart-20-solid',
- selectedIconClass: 'i-heroicons-shopping-cart-20-solid',
- },
- {
- key: 'profile',
- title: '我的',
- iconClass: 'i-heroicons-user-20-solid',
- selectedIconClass: 'i-heroicons-user-20-solid',
- },
- ]
- export const TabBarLayout: React.FC<TabBarLayoutProps> = ({ children, activeKey }) => {
- const { cart } = useCart()
- const cartItemCount = cart.items.reduce((sum, item) => sum + item.quantity, 0)
- const handleTabChange = (key: string) => {
- // 使用 Taro 的导航 API 进行页面跳转
- switch (key) {
- case 'home':
- Taro.switchTab({ url: '/pages/index/index' })
- break
- case 'category':
- Taro.switchTab({ url: '/pages/category/index' })
- break
- case 'cart':
- Taro.switchTab({ url: '/pages/cart/index' })
- break
- case 'profile':
- Taro.switchTab({ url: '/pages/profile/index' })
- break
- default:
- break
- }
- }
- // 动态设置购物车标签的角标
- const tabItemsWithBadge = tabBarItems.map(item => {
- if (item.key === 'cart' && cartItemCount > 0) {
- return {
- ...item,
- badge: cartItemCount > 99 ? '99+' : cartItemCount
- }
- }
- return item
- })
- return (
- <View className="min-h-screen bg-gray-50 flex flex-col">
- <View className="flex-1 flex flex-col">
- {children}
- </View>
- <TabBar
- items={tabItemsWithBadge}
- activeKey={activeKey}
- onChange={handleTabChange}
- fixed={true}
- safeArea={true}
- selectedColor='#fa4126'
- />
- </View>
- )
- }
- export default TabBarLayout
|