reactjs - 在 useGesture React 中为拖动元素添加边界和初始位置
问题描述
在阅读了 useGesture 的文档并尝试添加边界(限制拖动元素的空间)后,我找不到让它工作的方法。所以,我需要弄清楚如何添加它们,还要添加一些“软边界”以知道元素何时通过这些边界自动旋转 90 级,还需要弄清楚设置元素的初始位置,因为我需要从屏幕中心开始。
这是拖动组件:
import React, { useRef, useState } from 'react'
import { useSpring, animated } from '@react-spring/web'
import { useGesture } from 'react-use-gesture'
import './styles.css'
const calcX = (y, ly) => -(y - ly - window.innerHeight / 2) / 20
const calcY = (x, lx) => (x - lx - window.innerWidth / 2) / 20
document.addEventListener('gesturestart', (e) => e.preventDefault())
document.addEventListener('gesturechange', (e) => e.preventDefault())
const Dragable = ({ children }) => {
const domTarget = useRef(null)
const [{ x, y }, set] = useSpring(() => ({
x: 0,
y: 0,
config: {
mass: 5,
tension: 350,
friction: 40,
},
}))
const [drag, setDrag] = useState(false)
useGesture(
{
onDragStart: () => setDrag(true),
// eslint-disable-next-line no-shadow
onDrag: ({ offset: [x, y] }) => set({ x, y }),
onDragEnd: () => setDrag(false),
onMove: ({ xy: [px, py], dragging }) =>
!dragging &&
set({
rotateX: calcX(py, y.get()),
rotateY: calcY(px, x.get()),
}),
},
{
domTarget,
eventOptions: { passive: false },
}
)
return (
<animated.div
ref={domTarget}
className={`${drag ? 'dragging' : ''} fixShit`}
style={{
transform: 'perspective(600px)',
x,
y,
}}
>
{children}
</animated.div>
)
}
export default Dragable
此示例是否相同-> https://codesandbox.io/s/pedantic-carson-mefip?file=/src/App.tsx
谢谢,
解决方案
推荐阅读
- javascript - 巧克力js从链接attr href打开图像
- reactjs - 从帖子中删除评论:评论不会删除或错误的评论被删除,commentId undefined
- ansible - ansible jinja2 - if elseif - 使用相同的行
- typescript - 将reduce与map和array一起使用
- python - 在 django 模板中显示 PIL 图像对象
- react-native - 无法验证自定义博览会客户的身份
- javascript - 如果值为 false,则删除变量
- swift - 如何使用 xmlcoder 解码 xml?
- angular - Rxjs 观察者过滤器不工作错误
- apache-spark - 如何在pyspark的循环中合并数据帧