Use Gesture是一个支持丰富鼠标和触摸手势的 React 库 。Use Gesture可以将丰富的鼠标和事件绑定到任何组件或视图。通过接收到的数据,设置手势变得非常简单,而且通常只需要几行代码。
Npm
npm i @use-gesture/react
Yarn
yarn add @use-gesture/react
Npm
npm i @use-gesture/vanilla
Yarn
yarn add @use-gesture/vanilla
import { useSpring, animated } from '@react-spring/web'
import { useDrag } from '@use-gesture/react'
function Example() {
const [{ x, y }, api] = useSpring(() => ({ x: 0, y: 0 }))
// Set the drag hook and define component movement based on gesture data
const bind = useDrag(({ down, movement: [mx, my] }) => {
api.start({ x: down ? mx : 0, y: down ? my : 0 })
})
// Bind it to a component
return <animated.div {...bind()} style={{ x, y, touchAction: 'none' }} />
}
<!-- index.html -->
<div id="drag" />
// script.js
const el = document.getElementById('drag')
const gesture = new DragGesture(el, ({ active, movement: [mx, my] }) => {
setActive(active)
anime({
targets: el,
translateX: active ? mx : 0,
translateY: active ? my : 0,
duration: active ? 0 : 1000
})
})
// when you want to remove the listener
gesture.destroy()
Github地址:
https://github.com/pmndrs/use-gesture
End