前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >一个支持丰富鼠标和触摸手势的 React 库

一个支持丰富鼠标和触摸手势的 React 库

作者头像
老鱼的日常
发布2023-08-25 10:53:49
2880
发布2023-08-25 10:53:49
举报
文章被收录于专栏:程序员老鱼呀程序员老鱼呀

Use Gesture是一个支持丰富鼠标和触摸手势的 React 库 。Use Gesture可以将丰富的鼠标和事件绑定到任何组件或视图。通过接收到的数据,设置手势变得非常简单,而且通常只需要几行代码。

安装

React

Npm

代码语言:javascript
复制
npm i @use-gesture/react

Yarn

代码语言:javascript
复制
yarn add @use-gesture/react

纯JavaScript:

Npm

代码语言:javascript
复制
npm i @use-gesture/vanilla

Yarn

代码语言:javascript
复制
yarn add @use-gesture/vanilla

使用

react

代码语言:javascript
复制
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' }} />
}

javascript

代码语言:javascript
复制
<!-- index.html -->
<div id="drag" />
代码语言:javascript
复制
// 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

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2023-08-23,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 老鱼的日常 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 安装
    • React
      • 纯JavaScript:
      • 使用
        • react
          • javascript
          领券
          问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档