|
| 1 | +import { useRef } from 'react' |
| 2 | +import { useDrag } from '@use-gesture/react' |
| 3 | + |
| 4 | +function TestDrag() { |
| 5 | + const bind = useDrag(({ offset: [x, y], event }) => { |
| 6 | + event.currentTarget.style.transform = `translate(${x}px,${y}px)` |
| 7 | + }) |
| 8 | + |
| 9 | + return ( |
| 10 | + <div |
| 11 | + {...bind()} |
| 12 | + style={{ |
| 13 | + width: '100px', |
| 14 | + height: '100px', |
| 15 | + backgroundColor: '#ff0000', |
| 16 | + touchAction: 'none' |
| 17 | + }} |
| 18 | + /> |
| 19 | + ) |
| 20 | +} |
| 21 | +function TestNaiveDrag() { |
| 22 | + const dragging = useRef(false) |
| 23 | + const initial = useRef([0, 0]) |
| 24 | + const px = useRef(0) |
| 25 | + const py = useRef(0) |
| 26 | + const x = useRef(0) |
| 27 | + const y = useRef(0) |
| 28 | + |
| 29 | + const onPointerDown = (e) => { |
| 30 | + e.currentTarget.setPointerCapture(e.pointerId) |
| 31 | + initial.current = [e.clientX, e.clientY] |
| 32 | + px.current = x.current |
| 33 | + py.current = y.current |
| 34 | + dragging.current = true |
| 35 | + } |
| 36 | + |
| 37 | + const onPointerMove = (e) => { |
| 38 | + if (!dragging.current) return |
| 39 | + x.current = px.current + e.clientX - initial.current[0] |
| 40 | + y.current = py.current + e.clientY - initial.current[1] |
| 41 | + e.currentTarget.style.transform = `translate(${x.current}px,${y.current}px)` |
| 42 | + } |
| 43 | + |
| 44 | + const onPointerUp = (e) => { |
| 45 | + dragging.current = false |
| 46 | + } |
| 47 | + |
| 48 | + return ( |
| 49 | + <div |
| 50 | + onPointerDown={onPointerDown} |
| 51 | + onPointerMove={onPointerMove} |
| 52 | + onPointerUp={onPointerUp} |
| 53 | + style={{ |
| 54 | + width: '100px', |
| 55 | + height: '100px', |
| 56 | + backgroundColor: '#00ff00', |
| 57 | + touchAction: 'none' |
| 58 | + }} |
| 59 | + /> |
| 60 | + ) |
| 61 | +} |
| 62 | + |
| 63 | +export default function App() { |
| 64 | + return ( |
| 65 | + <div> |
| 66 | + <TestDrag /> |
| 67 | + <TestNaiveDrag /> |
| 68 | + </div> |
| 69 | + ) |
| 70 | +} |
0 commit comments