首页
/ 使用 @use-gesture 库的教程

使用 @use-gesture 库的教程

2026-01-17 08:46:54作者:翟萌耘Ralph

项目介绍

@use-gesture 是一个强大的库,允许你将更丰富的鼠标和触摸事件绑定到任何组件或视图。通过接收到的数据,设置手势变得非常简单,通常只需几行代码。你可以单独使用它,但为了充分发挥其功能,建议与动画库(如 react-spring)结合使用。

项目快速启动

安装

React

使用 Yarn 安装:

yarn add @use-gesture/react

使用 NPM 安装:

npm install @use-gesture/react

Vanilla JavaScript

使用 Yarn 安装:

yarn add @use-gesture/vanilla

使用 NPM 安装:

npm install @use-gesture/vanilla

示例代码

React

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' }} />
}

Vanilla JavaScript

<!-- index.html -->
<div id="drag"></div>

<!-- 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()

应用案例和最佳实践

拖拽组件

使用 useDrag 钩子可以轻松实现组件的拖拽功能。以下是一个简单的示例:

import { useSpring, animated } from '@react-spring/web'
import { useDrag } from '@use-gesture/react'

function DraggableComponent() {
  const [[x, y], api] = useSpring(() => ({ x: 0, y: 0 }))

  const bind = useDrag(({ down, movement: [mx, my] }) => {
    api.start({ x: down ? mx : 0, y: down ? my : 0 })
  })

  return <animated.div {...bind()} style={{ x, y, touchAction: 'none' }} />
}

缩放手势

使用 usePinch 钩子可以实现缩放手势:

import { useSpring, animated } from '@react-spring/web'
import { usePinch } from '@use-gesture/react'

function PinchableComponent() {
  const [scale, api] = useSpring(() => ({ scale: 1 }))

  const bind = usePinch(({ offset: [d] }) => {
    api.start({ scale: d })
  })

  return <animated.div {...bind()} style={{ scale, touchAction: 'none' }} />
}

典型生态项目

React-Spring

@use-gesture 通常与 react-spring 结合使用,以实现平滑的动画效果。react-spring 是一个基于弹簧物理的动画库,可以与 @use-gesture 无缝集成。

Anime.js

对于 Vanilla JavaScript 项目,可以与 Anime.js 结合使用,实现复杂的动画效果。Anime.js 是一个轻量级的 JavaScript 动画库,具有简单而强大的 API。

通过这些生态项目的结合使用,可以大大增强 @use-gesture 的功能和表现力。

登录后查看全文
热门项目推荐
相关项目推荐