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>
相关推荐
C_心欲无痕1 小时前
前端实现水印的两种方式:SVG 与 Canvas
前端·安全·水印
尾善爱看海4 小时前
不常用的浏览器 API —— Web Speech
前端
美酒没故事°5 小时前
vue3拖拽+粘贴的综合上传器
前端·javascript·typescript
jingling5556 小时前
css进阶 | 实现罐子中的水流搅拌效果
前端·css
酷酷的鱼6 小时前
跨平台技术选型方案(2026年App实战版)
react native·架构·鸿蒙系统
悟能不能悟7 小时前
前端上载文件时,上载多个文件,但是一个一个调用接口,怎么实现
前端
可问春风_ren8 小时前
前端文件上传详细解析
前端·ecmascript·reactjs·js
羊小猪~~9 小时前
【QT】--文件操作
前端·数据库·c++·后端·qt·qt6.3
晚风资源组9 小时前
CSS文字和图片在容器内垂直居中的简单方法
前端·css·css3
Miketutu10 小时前
Flutter学习 - 组件通信与网络请求Dio
开发语言·前端·javascript