| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546 |
- import { useRef, useCallback } from 'react';
- interface UseTouchDoubleClickOptions {
- onDoubleClick: () => void;
- delay?: number; // 双击间隔时间,默认300ms
- }
- export const useTouchDoubleClick = ({
- onDoubleClick,
- delay = 300,
- }: UseTouchDoubleClickOptions) => {
- const touchTimeRef = useRef<number>(0);
- const touchCountRef = useRef<number>(0);
- const handleTouchStart = useCallback(
- (e: React.TouchEvent) => {
- console.log(`${e.type} event detected`);
- const now = Date.now();
- const timeDiff = now - touchTimeRef.current;
- if (timeDiff < delay && timeDiff > 0) {
- touchCountRef.current += 1;
- if (touchCountRef.current === 2) {
- onDoubleClick();
- touchCountRef.current = 0;
- touchTimeRef.current = 0;
- return;
- }
- } else {
- touchCountRef.current = 1;
- }
- touchTimeRef.current = now;
- // 重置计数器
- setTimeout(() => {
- if (touchCountRef.current === 1) {
- touchCountRef.current = 0;
- }
- }, delay);
- },
- [onDoubleClick, delay]
- );
- return { handleTouchStart };
- };
|