react native 使用ScrollView实现轮播图效果

废话不多说,直接上代码(由于功能比较简单就没必要简述了)

javascript 复制代码
// 轮播图的业务逻辑
startAutoPlay (data) {
    // data: 图片的数据列表
    if (this.scrollViewRef) {
      this.interval = setInterval(() => {
        const { currentIndex, itemWidth } = this.state;
        const nextIndex = (currentIndex + 1) % data.length;
        this.setState({ currentIndex: nextIndex });
        let isAnimated = true
        // 最后一张切换到第一张不要做动画
        if(nextIndex == 0){
          isAnimated = false
        }
        this.scrollViewRef.scrollTo({ x: nextIndex * itemWidth, animated: isAnimated });
      }, 2000);
    }
  }

  // 组件销毁清除定时器
  stopAutoPlay () {
    clearInterval(this.interval);
  }
javascript 复制代码
               // 轮播图的View
               <View style={styles.mainWarp}>
                  {
                    this.state.list.length > 0 && (
                      <ScrollView
                        ref={
                          ref => {
                            this.scrollViewRef = ref
                          }
                        }
                        horizontal
                        pagingEnabled
                        showsHorizontalScrollIndicator={false}
                      >
                        {this.state.list.map((item, index) => (
                          <Image
                            key={index}
                            source={{ uri: item.path }}
                            style={styles.itemImage}
                          />
                        ))}
                      </ScrollView>
                    )
                  }
                </View>
相关推荐
用户033307413959 分钟前
TypeScript using 与 AsyncDisposableStack:在真实服务端代码中协调多资源清理
前端
daisychey16 分钟前
用 Playwright 做多平台内容分发,我踩过的 8 个坑
前端
enjoywindstorm18 分钟前
移动端原生框架对比评测
react native
IT_陈寒1 小时前
为什么你应该学习JavaScript?
前端·人工智能·后端
大龄秃头程序员2 小时前
iOS冷启动监控Demo
前端
光影少年2 小时前
为什么 JavaScript 中 0.1 + 0.2 !== 0.3,如何让其相等?
前端·javascript·算法
掘金酱2 小时前
[稀土掘金 × 火山引擎] AI用量周榜冲刺赛|获奖名单公示
前端·人工智能·后端
泡泡oO2 小时前
“如果你还在用Superpowers,那我不要和你说话”
前端·后端·全栈
维克兜率天3 小时前
趋势过滤:避免被“假突破“反复打脸
前端
8年区块链老兵3 小时前
一篇文章教会你:用区块高度读懂比特币链上的每一笔交易
前端