useTouchDoubleClick.ts 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import { useRef, useCallback } from 'react';
  2. interface UseTouchDoubleClickOptions {
  3. onDoubleClick: () => void;
  4. delay?: number; // 双击间隔时间,默认300ms
  5. }
  6. export const useTouchDoubleClick = ({
  7. onDoubleClick,
  8. delay = 300,
  9. }: UseTouchDoubleClickOptions) => {
  10. const touchTimeRef = useRef<number>(0);
  11. const touchCountRef = useRef<number>(0);
  12. const handleTouchStart = useCallback(
  13. (e: React.TouchEvent) => {
  14. console.log(`${e.type} event detected`);
  15. const now = Date.now();
  16. const timeDiff = now - touchTimeRef.current;
  17. if (timeDiff < delay && timeDiff > 0) {
  18. touchCountRef.current += 1;
  19. if (touchCountRef.current === 2) {
  20. onDoubleClick();
  21. touchCountRef.current = 0;
  22. touchTimeRef.current = 0;
  23. return;
  24. }
  25. } else {
  26. touchCountRef.current = 1;
  27. }
  28. touchTimeRef.current = now;
  29. // 重置计数器
  30. setTimeout(() => {
  31. if (touchCountRef.current === 1) {
  32. touchCountRef.current = 0;
  33. }
  34. }, delay);
  35. },
  36. [onDoubleClick, delay]
  37. );
  38. return { handleTouchStart };
  39. };