import React, { useState, useRef, useEffect } from 'react' /** * SegmentedControl 多选项水平切换控件 * * 用法: * setSelected(val)} * /> * * 选中项背景滑动动画(transform: translateX) * 支持 disabled 选项 */ export interface SegmentOption { label: string value: string disabled?: boolean } interface SegmentedControlProps { options: SegmentOption[] value: string onChange: (value: string) => void className?: string size?: 'sm' | 'md' } export default function SegmentedControl({ options, value, onChange, className = '', size = 'md', }: SegmentedControlProps) { const containerRef = useRef(null) const [indicatorStyle, setIndicatorStyle] = useState({ left: 0, width: 0 }) const sizeClasses = size === 'sm' ? 'px-2.5 py-1 text-xs' : 'px-3.5 py-2 text-sm' // 计算选中指示器位置 useEffect(() => { if (!containerRef.current) return const activeIndex = options.findIndex((o) => o.value === value) const buttons = containerRef.current.querySelectorAll('[data-segment]') if (activeIndex < 0 || !buttons[activeIndex]) return const containerRect = containerRef.current.getBoundingClientRect() const activeRect = buttons[activeIndex].getBoundingClientRect() setIndicatorStyle({ left: activeRect.left - containerRect.left, width: activeRect.width, }) }, [value, options]) return (
{/* 滑动背景指示器 */}
{options.map((opt) => ( ))}
) }