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>
相关推荐
!win !3 小时前
前端跨标签页通信方案(下)
前端·javascript
f***45323 小时前
基于SpringBoot和PostGIS的各省与地级市空间距离分析
android·前端·后端
编码追梦人3 小时前
从 “手忙脚乱“ 到 “行云流水“:华为云 DevUI 与 MateChat 如何让前端开发飞起来
前端·华为云
用户47949283569154 小时前
TypeScript 简史:它是怎么拯救我的烂代码的
javascript·typescript
S***H2834 小时前
前端动画实现经验,性能优化与兼容性
前端
用户47949283569154 小时前
只有前端 Leader 才会告诉你:那些年踩过的模块加载失败的坑(二)
javascript
xw54 小时前
前端跨标签页通信方案(下)
前端·javascript
zzlyx995 小时前
IoTSharp前端VUE采用npm run build编译提示require() of ES Module 出错
前端·vue.js·npm
全栈技术负责人5 小时前
拒绝“无法复现”:前端全链路日志排查实战手册
前端·全链路·问题排查思路
加洛斯5 小时前
前端小知识003:JS中 == 与 === 的区别
开发语言·前端·javascript