import React from 'react' import { View, Text } from '@tarojs/components' import { cn } from '@/utils/cn' import Taro from '@tarojs/taro' import { isWeapp } from '@/utils/platform' export interface NavbarProps { title?: string leftText?: string leftIcon?: string rightText?: string rightIcon?: string backgroundColor?: string textColor?: string border?: boolean fixed?: boolean placeholder?: boolean onClickLeft?: () => void onClickRight?: () => void children?: React.ReactNode className?: string /** 是否在小程序环境下隐藏右侧按钮(默认false,会自动避让) */ hideRightInWeapp?: boolean } const systemInfo = Taro.getSystemInfoSync() const menuButtonInfo = Taro.getMenuButtonBoundingClientRect() // 计算导航栏高度 const NAVBAR_HEIGHT = 44 const STATUS_BAR_HEIGHT = systemInfo.statusBarHeight || 0 const TOTAL_HEIGHT = STATUS_BAR_HEIGHT + NAVBAR_HEIGHT export const Navbar: React.FC = ({ title, leftText, leftIcon = 'i-heroicons-chevron-left-20-solid', rightText, rightIcon, backgroundColor = 'bg-white', textColor = 'text-gray-900', border = true, fixed = true, placeholder = true, onClickLeft, onClickRight, children, className, hideRightInWeapp, }) => { // 处理左侧点击 const handleLeftClick = () => { if (onClickLeft) { onClickLeft() } else { // 默认返回上一页 Taro.navigateBack() } } // 渲染左侧内容 const renderLeft = () => { if (children) return null return ( {leftIcon && ( )} {leftText && ( {leftText} )} ) } // 渲染右侧内容 const renderRight = () => { if (!rightText && !rightIcon || (hideRightInWeapp && isWeapp())) return null if (isWeapp() && menuButtonInfo) { // 小程序环境下,调整右侧按钮位置 return ( {rightText && ( {rightText} )} {rightIcon && ( )} ) } // H5或其他平台,保持原有样式 return ( {rightText && ( {rightText} )} {rightIcon && ( )} ) } // 渲染标题 const renderTitle = () => { if (children) return children if (isWeapp() && menuButtonInfo) { // 小程序环境下,调整标题位置 return ( {title} ) } // H5或其他平台,保持原有样式 return ( {title} ) } // 导航栏样式 const navbarStyle = { height: TOTAL_HEIGHT, paddingTop: STATUS_BAR_HEIGHT, } return ( <> {/* 导航栏内容 */} {renderLeft()} {renderTitle()} {renderRight()} {/* 占位元素 */} {fixed && placeholder && ( )} ) } // 预设样式 export const NavbarPresets = { // 默认白色导航栏 default: { backgroundColor: 'bg-white', textColor: 'text-gray-900', border: true, }, // 深色导航栏 dark: { backgroundColor: 'bg-gray-900', textColor: 'text-white', border: true, }, // 透明导航栏 transparent: { backgroundColor: 'bg-transparent', textColor: 'text-white', border: false, }, // 主色调导航栏 primary: { backgroundColor: 'bg-blue-500', textColor: 'text-white', border: false, }, } // 快捷创建函数 export const createNavbar = (preset: keyof typeof NavbarPresets) => { return NavbarPresets[preset] } export default Navbar