拖动不适用于反应使用手势

Dragging not working for react-use-gesture

出于某种原因,我无法让最基本的 react-use-gesture 示例发挥作用。我想做的是在拖动时让一个正方形跟随我的鼠标位置。我多次从他们的文档中复制粘贴示例 (https://github.com/pmndrs/react-use-gesture),但仍然无法正常工作。我只是不明白了。我创建了一个 stackblitz 来向您展示我的代码。我还做错了什么?

Stackblitz 代码:https://stackblitz.com/edit/react-mg2u8p?file=src/Square.js

我还将在此处包含最相关的代码:

import React from "react";
import { useSpring, animated } from "react-spring";
import { useDrag } from "react-use-gesture";

const Square = () => {
  const [{ x, y }, set] = useSpring(() => ({ x: 0, y: 0 }));
  const bind = useDrag(({ down, movement: [mx, my] }) => {
    set({ x: down ? mx : 0, y: down ? my : 0 });
  });

  return (
    <animated.div
      {...bind()}
      className="Square"
      style={{ x, y, touchAction: "none" }}
    />
  );
};

export default Square;

版本问题

您的示例使用 react-spring 版本 9+ 的代码,但您在示例中使用的 react-spring 版本是 8.0.27.

文档为版本 8 提供的示例是这样的:

import { useSpring, animated } from 'react-spring'
import { useDrag } from 'react-use-gesture'

function PullRelease() {
  const [{ xy }, set] = useSpring(() => ({ xy: [0, 0] }))
  // Set the drag hook and define component movement based on gesture data
  const bind = useDrag(({ down, movement }) => {
    set({ xy: down ? movement : [0, 0] })
  })
  // Bind it to a component
  return (
    <animated.div
      {...bind()}
      style={{
        transform: xy.interpolate((x, y) => `translate3d(${x}px, ${y}px, 0)`),
      }}
    />
  )
}

所以在你的情况下,你只需要将 PullRelease 更改为 Square 并将 className="Square" 添加到 animated.div 就像你在你的问题中那样。


有关使用 React UseGesture 实现的 v8v9 的文档,请参阅 this

如果要使用v9版本,目前需要根据文档安装react-spring@next(参见之前的link)。