【发布时间】:2022-01-06 19:41:22
【问题描述】:
我目前正在开发一个 React 应用,我想检测 div 元素(在移动设备上)上的滑动事件(左、右)。
如何在没有任何额外库的情况下实现这一目标?
【问题讨论】:
标签: reactjs mobile event-handling touch
我目前正在开发一个 React 应用,我想检测 div 元素(在移动设备上)上的滑动事件(左、右)。
如何在没有任何额外库的情况下实现这一目标?
【问题讨论】:
标签: reactjs mobile event-handling touch
此代码检测左右滑动事件,对通常的触摸事件没有任何影响。
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)。
【讨论】: