首页 > 解决方案 > 在 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

谢谢,

标签: reactjsdraggabledragreact-springreact-use-gesture

解决方案


推荐阅读