import { useCallback, useEffect, useRef, useState } from 'react'; interface SteerButtonProps { icon: React.ReactNode; label: string; color: string; onPressStart?: () => void; onPressEnd?: () => void; interval?: number; } const SteerButton = ({ icon, label, color, onPressStart, onPressEnd, interval = 100, }: SteerButtonProps) => { const [pressed, setPressed] = useState(false); // 是否处于按下状态 const holdingRef = useRef(false); // 定时发送句柄 const timerRef = useRef | null>(null); // 保存最新的回调,避免定时器使用过期闭包 const onPressStartRef = useRef(onPressStart); const onPressEndRef = useRef(onPressEnd); useEffect(() => { onPressStartRef.current = onPressStart; }, [onPressStart]); useEffect(() => { onPressEndRef.current = onPressEnd; }, [onPressEnd]); // 停止长按 const stopHold = useCallback(() => { if (!holdingRef.current) return; holdingRef.current = false; if (timerRef.current !== null) { clearTimeout(timerRef.current); timerRef.current = null; } setPressed(false); // 只在有效按压结束时发送一次释放数据 onPressEndRef.current?.(); }, []); // 开始长按 const startHold = useCallback(() => { // 防止重复触发 if (holdingRef.current) return; holdingRef.current = true; setPressed(true); // 立即发送第一帧 onPressStartRef.current?.(); // 持续发送 const scheduleNext = () => { if (!holdingRef.current) return; timerRef.current = setTimeout(() => { if (!holdingRef.current) return; onPressStartRef.current?.(); scheduleNext(); }, interval); }; scheduleNext(); }, [interval]); // 组件卸载时清理定时器 useEffect(() => { return () => { holdingRef.current = false; if (timerRef.current !== null) { clearTimeout(timerRef.current); timerRef.current = null; } }; }, []); return ( ); }; export default SteerButton;