【问题标题】:How do I recognize swipe events in React?如何识别 React 中的滑动事件?
【发布时间】:2022-01-06 19:41:22
【问题描述】:

我目前正在开发一个 React 应用,我想检测 div 元素(在移动设备上)上的滑动事件(左、右)。

如何在没有任何额外库的情况下实现这一目标?

【问题讨论】:

    标签: reactjs mobile event-handling touch


    【解决方案1】:

    水平滑动(左、右)

    此代码检测左右滑动事件,对通常的触摸事件没有任何影响。

    const [touchStart, setTouchStart] = useState(null)
    const [touchEnd, setTouchEnd] = useState(null)
    
    // the required distance between touchStart and touchEnd to be detected as a swipe
    const minSwipeDistance = 50 
    
    const onTouchStart = (e) => {
      setTouchEnd(null) // otherwise the swipe is fired even with usual touch events
      setTouchStart(e.targetTouches[0].clientX)
    }
    
    const onTouchMove = (e) => setTouchEnd(e.targetTouches[0].clientX)
    
    const onTouchEnd = () => {
      if (!touchStart || !touchEnd) return
      const distance = touchStart - touchEnd
      const isLeftSwipe = distance > minSwipeDistance
      const isRightSwipe = distance < -minSwipeDistance
      if (isLeftSwipe || isRightSwipe) console.log('swipe', isLeftSwipe ? 'left' : 'right')
      // add your conditional logic here
    }
    
    <div onTouchStart={onTouchStart} onTouchMove={onTouchMove} onTouchEnd={onTouchEnd}/>
    

    垂直滑动(上、下)

    如果您还需要检测垂直滑动(上下),您可以以类似的方式使用e.targetTouches[0].clientY(请参阅docs)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-08
      • 1970-01-01
      • 2022-11-08
      • 2020-10-20
      • 2018-06-14
      • 1970-01-01
      • 1970-01-01
      • 2016-08-04
      相关资源
      最近更新 更多