Skip to content

Latest commit

 

History

History
117 lines (105 loc) · 4.58 KB

react-use-gesture.mdx

File metadata and controls

117 lines (105 loc) · 4.58 KB
id title sidebar_label
react-use-gesture
react-use-gesture
react-use-gesture

需求

  • requestAnimationFrame

使用

import React from 'react'
import { View } from '@tarojs/components'
import { useDrag } from 'react-use-gesture'
import { useGestureConfig } from '@tarojsx/library/dist/react-use-gesture'

const Demo = () => {
    const [gestureConfig, containerProps] = useGestureConfig()

    const bind = useDrag(({ down, movement: [mx, my], direction: [xDir, yDir], distance, cancel }) => {
        console.log('按下', down)
        console.log('轴移动距离', mx, my)
        console.log('轴移动方向', xDir, yDir)
        console.log('直线移动距离', distance)
        console.log('取消拖动操作', cancel)
    }, gestureConfig)

    return <View {...containerProps}>{<View {...bind()} />}</View>
}

import { useRef, useMemo } from 'react' import Taro from '@tarojs/taro' import _clamp from 'lodash/clamp' import { useGestureConfig, useDrag } from '@tarojsx/library/dist/react-use-gesture' import { animated, useSprings } from '@tarojsx/library/dist/react-spring' import { View } from '@tarojs/components' import { UI } from '@/ui'

{() => { const { windowWidth } = useMemo(() => Taro.getSystemInfoSync(), []) const pages = useMemo( () => [ 'https://img11.360buyimg.com/uba/jfs/t21205/91/853520716/145629/b03d7fa7/5b19f383N6a30536b.jpg', 'https://img14.360buyimg.com/ling/jfs/t1/103557/3/12087/1051626/5e44b357E4cab8765/d8c821c4a3e1060d.png', 'https://storage.360buyimg.com/taro-club-img/b42116392c909d0680788853011c70db', 'https://storage.jd.com/taro-resource/review.jpg', 'https://misc.aotu.io/jimczj/2018-08-27taro-ui.jpg', 'https://img10.360buyimg.com/img/jfs/t1/21860/12/8740/42390/5c790470E1d0bbce9/9f9bb78d01f7564b.png', ], [] ) const [gestureConfig, containerProps] = useGestureConfig() const index = useRef(0) const [springs, set] = useSprings(pages.length, (i) => ({ x: i * 2 * windowWidth, sc: 1, display: 'block' })) const drag = useDrag((e) => { const { down, direction: [xDir], distance, cancel, } = e console.log('useDrag', 'distance', distance) if (down && distance > windowWidth / 2) { index.current = _clamp(index.current + (xDir > 0 ? -1 : 1), 0, pages.length - 1) cancel() } set((i) => { if (i < index.current - 1 || i > index.current + 1) return { display: 'none' } const x = (i - index.current) * 2 * windowWidth + (down ? xDir * distance : 0) const sc = down ? 1 - distance / windowWidth / 2 : 1 return { x, sc, display: 'block' } }) }, gestureConfig) return ( ⬅ 拖拽图片 ➡ {springs.map(({ x, display, sc }, i) => ( `translate3d(${x}px,0,0)`), }} > `scale(${s})`), background: `center / contain no-repeat url(${pages[i]})`, }} /> ))} ) }}
参数 说明 类型 默认值
id? 容器元素 ID string uuid
ref? React ref
返回值 说明 类型
[0] gestureConfig: 传给 react-use-gesture hooks 的配置 {}
[1] containerProps: 需要绑定在容器元素上的属性