tab-bar-layout.tsx 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. import React, { ReactNode } from 'react'
  2. import { View } from '@tarojs/components'
  3. import { TabBar, TabBarItem } from '@/components/ui/tab-bar'
  4. import Taro from '@tarojs/taro'
  5. import { useCart } from '@/contexts/CartContext'
  6. export interface TabBarLayoutProps {
  7. children: ReactNode
  8. activeKey: string
  9. }
  10. const tabBarItems: TabBarItem[] = [
  11. {
  12. key: 'home',
  13. title: '首页',
  14. iconClass: 'i-heroicons-home-20-solid',
  15. selectedIconClass: 'i-heroicons-home-20-solid',
  16. },
  17. {
  18. key: 'category',
  19. title: '分类',
  20. iconClass: 'i-heroicons-squares-2x2-20-solid',
  21. selectedIconClass: 'i-heroicons-squares-2x2-20-solid',
  22. },
  23. {
  24. key: 'cart',
  25. title: '购物车',
  26. iconClass: 'i-heroicons-shopping-cart-20-solid',
  27. selectedIconClass: 'i-heroicons-shopping-cart-20-solid',
  28. },
  29. {
  30. key: 'profile',
  31. title: '我的',
  32. iconClass: 'i-heroicons-user-20-solid',
  33. selectedIconClass: 'i-heroicons-user-20-solid',
  34. },
  35. ]
  36. export const TabBarLayout: React.FC<TabBarLayoutProps> = ({ children, activeKey }) => {
  37. const { cart } = useCart()
  38. const cartItemCount = cart.items.reduce((sum, item) => sum + item.quantity, 0)
  39. const handleTabChange = (key: string) => {
  40. // 使用 Taro 的导航 API 进行页面跳转
  41. switch (key) {
  42. case 'home':
  43. Taro.switchTab({ url: '/pages/index/index' })
  44. break
  45. case 'category':
  46. Taro.switchTab({ url: '/pages/category/index' })
  47. break
  48. case 'cart':
  49. Taro.switchTab({ url: '/pages/cart/index' })
  50. break
  51. case 'profile':
  52. Taro.switchTab({ url: '/pages/profile/index' })
  53. break
  54. default:
  55. break
  56. }
  57. }
  58. // 动态设置购物车标签的角标
  59. const tabItemsWithBadge = tabBarItems.map(item => {
  60. if (item.key === 'cart' && cartItemCount > 0) {
  61. return {
  62. ...item,
  63. badge: cartItemCount > 99 ? '99+' : cartItemCount
  64. }
  65. }
  66. return item
  67. })
  68. return (
  69. <View className="min-h-screen bg-gray-50 flex flex-col">
  70. <View className="flex-1 flex flex-col">
  71. {children}
  72. </View>
  73. <TabBar
  74. items={tabItemsWithBadge}
  75. activeKey={activeKey}
  76. onChange={handleTabChange}
  77. fixed={true}
  78. safeArea={true}
  79. selectedColor='#fa4126'
  80. />
  81. </View>
  82. )
  83. }
  84. export default TabBarLayout