由于某些原因,我无法得到最基本的反应-使用手势的例子。我想做的是,当你拖动它的时候,让一个方块跟随我的鼠标位置。我从他们的文档中多次复制粘贴了这个示例(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;
发布于 2021-01-20 21:04:20
这是版本问题。
您的示例使用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的v8和v9实现的文档,请参阅这。
如果您想使用v9版本,您目前需要根据文档安装react-spring@next (参见前面的链接)。
https://stackoverflow.com/questions/65816307
复制相似问题