如上图所示, 需要实现一个简单的上翻轮播图, 展示最新的三条数据
错误思路
onScroll={(event: any) => {
if (!this.state.autoPlay) return;
let y: any = event?.nativeEvent?.contentOffset.y
}}
以上方案通过y
的滚动只 y%固定高度 来获取index ,这种方案的缺陷在于依赖y
y
在滚动结束
实际返回中 会存在
30.12
60.21
这种误差, 求余数的结果就非常不准确
简单方案 – 延时+递归+判断下标
private setTimeAwait() {
return new Promise((resolve) => {
let time: any = setTimeout(() => {
clearTimeout(time)
time = null;
resolve();
}, this.delayTime)
})
}
private async startScrollAnimated() {
await this.setTimeAwait();
if (this.fastNewsScrollIndex == 2) {
this.fastNewsScrollIndex = 0
} else {
this.fastNewsScrollIndex += 1
}
this.doLoop();
}
private doLoop() {
this?.loopScroll?.scrollTo({
x: 0,
y: this.fastNewsItemH * this.fastNewsScrollIndex,
animated: this.fastNewsScrollIndex !== 0
})
this.startScrollAnimated();
}
小瑕疵 - 最后回归index==0的时候, 无动画/或者动画重置效应 ,
这种解决也简单, 把数据源复制成3个一组 ,复制多组即可, 把视觉效果加长到用户感知边际以外…