- Notifications
You must be signed in to change notification settings - Fork 1
Open
Description
问题描述
使用组件 react-native-swiper 时总会遇到的一个问题就是如何判断用户是向左滑还是向右滑,将文档看来看去都没有找到相关的属性或方法,只能自己去计算了。另一个问题是,在 swiper 是 loop 的情况下,快速滑动之后,如何知道滑动了多少个页面
解决方法
在 swiper中监听三个事件 onScrollBeginDrag、onScroll 和 onMomentumScrollEnd。onScrollBeginDrag 每滑一次都会触发,在这里记录 e.nativeEvent.contentOffset.x 的值(垂直方向滑动的话记录 e.nativeEvent.contentOffset.y)。在 onScroll 中再记录一次 e.nativeEvent.contentOffset.x 的值(onScroll会在onScrollBeginDrag之后触发)。最后在 onMomentumScrollEnd 中判断 onScroll 和 onScrollBeginDrag 中记录的偏移量就能判断滑动的方向了(onMomentumScrollEnd 只会在滑动动画完成后才会触发)。
另一个滑动多少页面的问题,由于 onScrollBeginDrag 每滑动一次都会触发,所以可以在 onScrollBeginDrag 里记录,但是有一种情况是你拖动了但又放回去,这时页面并没有切换,而 onScrollBeginDrag 却触发了,可以对比上一次的偏移量来过滤,页面没有切换时偏移量是一样的。代码如下:
onScrollBeginDrag (e) { if (e.nativeEvent.contentOffset.x !== this.offsetBegin) { this.scrollCount += 1 } else { return } this.offsetBegin = e.nativeEvent.contentOffset.y } onScroll (e) { this.offsetEnd = e.nativeEvent.contentOffset.y } onMomentumScrollEnd (e, state) { const { urls } = this.state let direction = '' if (this.offsetEnd - this.offsetBegin > 0) { direction = 'right' } else if (this.offsetEnd - this.offsetBegin < 0) { direction = 'left' } console.log('滑动方向:', direction) console.log('滑动页数:', this.scrollCount) this.scrollCount = 0 this.offsetBegin= -1 this.offsetEnd = -1 } 总结
如果 slider 不是 loop 的话可以通过 index 来判断,更简单
Metadata
Metadata
Assignees
Labels
No labels