如何封装长按 Hook 并区分点击与滑动

解读

国内面试中,这道题表面考“长按”,实则同时考察三项硬实力:

  1. 对 DOM 原生事件(mousedown/touchstart、mousemove/touchmove、mouseup/touchend、click)触发顺序与冒泡机制的精准理解;
  2. 在函数组件内用 Hook 做“事件注册-清理-状态同步”的闭环能力;
  3. 对“滑动”与“点击”阈值判定、性能节流、内存泄漏防范的工程化经验。

面试官通常会在你给出基础版本后追问:

  • 如何防止内存泄漏?
  • 如何兼容 PC 与移动端?
  • 阈值可配置吗?
  • 与滚动、拖拽、系统默认菜单冲突怎么办?
  • 用 Hooks 写一次,如何同时支持“单击”“双击”“长按”三种手势?

因此,答案必须体现“可配置、可清理、可扩展、无泄漏”四大特征,否则会被判为“仅会调库”。

知识点

  1. 事件触发顺序:
    mousedown/touchstart → mousemove/touchmove* → mouseup/touchend → click
    (*滑动时才触发)
  2. 长按判定:
    定时器 ≥ 阈值(默认 500 ms)且无显著位移(位移 ≤ 10 px)。
  3. 滑动判定:
    位移 > 10 px 即视为滑动,立即取消长按定时器并标记 isSwiped。
  4. 清理时机:
    组件卸载、依赖变化、手势结束时均须清理定时器与事件监听,防止内存泄漏。
  5. 节流/防抖:
    touchmove 高频触发,需节流 16 ms 级别避免频繁计算距离。
  6. 兼容性:
    同时监听 mouse 与 touch 事件,用 e.preventDefault() 阻止系统默认菜单,用 passive: false 显式声明。
  7. 可配置化:
    阈值、是否阻止默认、是否阻止冒泡、节流间隔全部参数化。
  8. TypeScript:
    返回的 ref 需约束为 MutableRefObject<HTMLElement | null>,事件回调类型精准。

答案

import { useRef, useEffect, useCallback } from 'react';

interface UseLongPressOptions {
  threshold?: number;          // 长按阈值,默认 500ms
  displacement?: number;       // 位移上限,默认 10px
  throttle?: number;           // touchmove 节流,默认 16ms
  preventDefault?: boolean;    // 是否阻止系统菜单
  stopPropagation?: boolean;   // 是否阻止冒泡
}

interface Point { x: number; y: number }

function getEventPoint(e: MouseEvent | TouchEvent): Point {
  const t = 'touches' in e ? e.touches[0] : e;
  return { x: t.clientX, y: t.clientY };
}

function distance(a: Point, b: Point): number {
  return Math.hypot(a.x - b.x, a.y - b.y);
}

export function useLongPress(
  onLongPress: (e: MouseEvent | TouchEvent) => void,
  options: UseLongPressOptions = {}
) {
  const {
    threshold = 500,
    displacement = 10,
    throttle = 16,
    preventDefault = true,
    stopPropagation = true,
  } = options;

  const targetRef = useRef<HTMLElement | null>(null);
  const timerRef = useRef<number | null>(null);
  const startRef = useRef<Point | null>(null);
  const isSwipedRef = useRef(false);
  const lastMoveRef = useRef(0);

  const clear = useCallback(() => {
    if (timerRef.current) {
      window.clearTimeout(timerRef.current);
      timerRef.current = null;
    }
    startRef.current = null;
    isSwipedRef.current = false;
  }, []);

  const onStart = useCallback(
    (e: MouseEvent | TouchEvent) => {
      if (preventDefault) e.preventDefault();
      if (stopPropagation) e.stopPropagation();
      clear();
      startRef.current = getEventPoint(e);
      timerRef.current = window.setTimeout(() => {
        if (!isSwipedRef.current) onLongPress(e);
        clear();
      }, threshold);
    },
    [onLongPress, threshold, preventDefault, stopPropagation, clear]
  );

  const onMove = useCallback(
    (e: MouseEvent | TouchEvent) => {
      const now = Date.now();
      if (now - lastMoveRef.current < throttle) return;
      lastMoveRef.current = now;

      if (!startRef.current) return;
      const cur = getEventPoint(e);
      if (distance(startRef.current, cur) > displacement) {
        isSwipedRef.current = true;
        clear();
      }
    },
    [displacement, throttle, clear]
  );

  const onEnd = useCallback(
    (e: MouseEvent | TouchEvent) => {
      if (preventDefault) e.preventDefault();
      clear();
    },
    [preventDefault, clear]
  );

  useEffect(() => {
    const el = targetRef.current;
    if (!el) return;

    el.addEventListener('mousedown', onStart);
    el.addEventListener('touchstart', onStart, { passive: !preventDefault });
    window.addEventListener('mousemove', onMove);
    window.addEventListener('touchmove', onMove, { passive: !preventDefault });
    window.addEventListener('mouseup', onEnd);
    window.addEventListener('touchend', onEnd);

    return () => {
      el.removeEventListener('mousedown', onStart);
      el.removeEventListener('touchstart', onStart);
      window.removeEventListener('mousemove', onMove);
      window.removeEventListener('touchmove', onMove);
      window.removeEventListener('mouseup', onEnd);
      window.removeEventListener('touchend', onEnd);
      clear();
    };
  }, [onStart, onMove, onEnd, preventDefault, clear]);

  return targetRef;
}

/* ===== 使用示例 ===== */
function Card() {
  const ref = useLongPress((e) => {
    console.log('长按触发', e.currentTarget);
  });

  return (
    <div ref={ref} className="card">
      长按我,滑动取消
    </div>
  );
}

要点回顾

  • 所有事件监听都在 useEffect 中统一注册与卸载,确保内存安全。
  • 滑动一旦超阈值立即取消定时器,避免“先滑动后误触发长按”。
  • 参数全部可配置,方便业务方按需调整。
  • 同时支持鼠标与触摸,覆盖 PC 与移动端。

拓展思考

  1. 组合手势:
    在同一元素上同时识别单击、双击、长按,可再封装 useGesture,内部维护一个“手势状态机”,通过记录点击次数与时间差实现。
  2. 多点长按:
    若需“双指长按”,可在 touchstart 里判断 e.touches.length === 2,并记录两个初始坐标。
  3. 可访问性:
    键盘用户无“长按”概念,可暴露同等功能的快捷键(如 Shift+Enter),并在 aria-label 中说明。
  4. 与滚动冲突:
    若父容器可滚动,需在 touchmove 里动态决定是否 e.preventDefault(),否则 iOS 会提前终止事件流;可引入 touch-action: none 样式做声明式隔离。
  5. 测试策略:
    使用 @testing-library/react + @testing-library/user-event 无法模拟真实长按,需要手写 fireEvent.mouseDown → wait(threshold) → fireEvent.mouseUp 并断言回调;对滑动测试则中间插入 fireEvent.mouseMove 并断言回调未被调用。
  6. 性能极限:
    在列表项级别(>1000 行)使用时,应为每个项加 React.memo,并在 Hook 内部用 useRef 缓存回调,避免父组件渲染导致子项反复注册监听。