使用 react-use-gesture 实现拖拽并设置边界约束

解读

国内一线/二线前端面试中,「拖拽 + 边界」是高频动效题,重点考察三点:

  1. 对 react-use-gesture(v10 之后并入 @use-gesture/react)API 的熟练度;
  2. 如何把「UI 像素空间」与「数据空间」映射,避免直接操作 DOM;
  3. 在 React 18 并发渲染下,如何保证动画不被打断、不掉帧。

边界约束通常有两种业务诉求:

  • 硬边界(绝对不可拖出容器);
  • 弹性边界(可拖出但松手回弹)。
    面试官希望你给出「可复用 Hook + 纯函数组件」的完整实现,并主动说出性能优化、SSR 安全、RTL 适配等工程细节。

知识点

  1. @use-gesture/react 的 drag 手势与 transform 模板字符串
  2. 基于 ref 的「容器尺寸」与「元素尺寸」实时测量(getBoundingClientRect / ResizeObserver)
  3. 利用 requestAnimationFrame 实现「先渲染、后测量」的异步边界校准,避免强制同步布局
  4. useSpring 物理动画做边界回弹(react-spring v9)
  5. 并发安全:把「拖拽偏移」放到 startTransition 外,防止高优更新被饿死
  6. 可访问性:拖拽同时同步更新 aria-valuenow,键盘操作兜底
  7. 测试策略:@testing-library/react + fireEvent.mouseMove 模拟边界碰撞场景

答案

// useBoundedDrag.ts
import { useDrag } from '@use-gesture/react';
import { useSpring, animated } from '@spring/react';
import { useRef, useLayoutEffect, useState } from 'react';

interface Options {
  boundId: string;          // 容器 id
  rubberband?: boolean;     // 是否弹性
  onDragEnd?: (xy: [number, number]) => void;
}

export function useBoundedDrag({ boundId, rubberband = true, onDragEnd }: Options) {
  const targetRef = useRef<HTMLDivElement>(null);
  const [{ x, y }, api] = useSpring(() => ({ x: 0, y: 0, config: { tension: 320, friction: 30 } }));

  const [bounds, setBounds] = useState<{
    left: number; top: number; right: number; bottom: number;
  }>({ left: 0, top: 0, right: 0, bottom: 0 });

  // 测量容器与元素尺寸
  useLayoutEffect(() => {
    const calc = () => {
      const container = document.getElementById(boundId);
      const el = targetRef.current;
      if (!container || !el) return;
      const cRect = container.getBoundingClientRect();
      const eRect = el.getBoundingClientRect();
      setBounds({
        left: 0,
        top: 0,
        right: cRect.width - eRect.width,
        bottom: cRect.height - eRect.height,
      });
    };
    calc();
    const ro = new ResizeObserver(calc);
    ro.observe(document.getElementById(boundId)!);
    return () => ro.disconnect();
  }, [boundId]);

  const bind = useDrag(
    ({ movement: [mx, my], dragging, velocity, direction, event }) => {
      event?.preventDefault(); // 防止选中文本
      let [tx, ty] = [mx, my];

      // 硬边界裁剪
      if (!rubberband) {
        tx = Math.max(bounds.left, Math.min(bounds.right, tx));
        ty = Math.max(bounds.top, Math.min(bounds.bottom, ty));
      }

      if (dragging) {
        api.start({ x: tx, y: ty, immediate: true });
      } else {
        // 松手后若越界则回弹
        const targetX = Math.max(bounds.left, Math.min(bounds.right, tx));
        const targetY = Math.max(bounds.top, Math.min(bounds.bottom, ty));
        api.start({ x: targetX, y: targetY });
        onDragEnd?.([targetX, targetY]);
      }
    },
    { bounds, rubberband, triggerAllEvents: true }
  );

  return [{ x, y }, bind, targetRef] as const;
}

// BoundedDrag.tsx
export default function BoundedDrag() {
  const [{ x, y }, bind, ref] = useBoundedDrag({
    boundId: 'container',
    rubberband: true,
  });

  return (
    <div id="container" className="w-96 h-96 relative border m-8 select-none">
      <animated.div
        {...bind()}
        ref={ref}
        className="w-20 h-20 bg-blue-500 rounded-md absolute cursor-grab active:cursor-grabbing touch-none"
        style={{ x, y, userSelect: 'none' }}
        role="slider"
        aria-valuemin={0}
        aria-valuemax={100}
        aria-valuenow={Math.round((x.get() / 276) * 100)} // 276 = 384-80
        aria-label="拖拽滑块"
      />
    </div>
  );
}

关键点讲解(面试口述)

  1. 用 useLayoutEffect + ResizeObserver 保证容器尺寸变化后边界实时更新,避免拖拽到“旧边界”外。
  2. immediate: true 让拖拽过程无弹簧,松手后再用 spring 回弹,符合 60 fps 体验。
  3. 把 bounds 对象直接传给 useDrag,库内部会自动应用 rubberband 系数,减少手写逻辑。
  4. 在 SSR 场景下,document.getElementById 只在客户端执行,不会导致 hydrate 错配。
  5. 若需要“网格吸附”,在 onDrag 里把 tx/ty 按 grid 尺寸取整即可,面试官会追问如何保持动画流畅——答案是把吸附逻辑放到 onDragEnd 里,用 spring 动画过去,而不是直接跳变。

拓展思考

  1. 多指触控:在移动端如果同时两指缩放,需要结合 usePinch 与 useDrag 做冲突仲裁,常用策略是「先触发的手势获胜」。
  2. 边界动态变化:当容器本身也在做 transform 动画(如侧边栏展开),需要把容器坐标映射到视口坐标,可用 getBoundingClientRect 的差值实时修正 bounds。
  3. 性能极限:列表内 200+ 可拖拽卡片时,把「活跃卡片」的 spring 动画放到 will-change: transform 图层,其余卡片用 translateZ(0) 提前提升,避免每次拖拽触发整片重排。
  4. 键盘无障碍:在 useBoundedDrag 里再包一层 useKeyboard,监听 ←→↑↓ 键,步长 10 px,Shift 加速 5 倍,同时把最终值同步到 aria-valuenow,让读屏用户知道位置。
  5. 测试覆盖:写一条「拖拽出边界松手回弹」的断言——用 @react-spring/testing 等待动画结束,再断言 x.get() 等于 bounds.right,证明回弹逻辑正确;国内 CI 普遍用 Jest + jsdom,需要 mock getBoundingClientRect 返回固定尺寸,避免环境差异导致用例 flaky。