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>
相关推荐
const_qiu1 小时前
第一章 1.1-1.2:基础模型调用与 TypeScript 入门 —— Java 开发者的视角
java·javascript·typescript
风骏时光牛马1 小时前
用户管理模块接口开发
前端
彭亚川Allen1 小时前
从零手搓 RAG 之检索全流程,给大模型接上自己的知识库
前端·后端·ai编程
IT_陈寒1 小时前
别让Java字符串拼接偷偷吃掉你的内存
前端·人工智能·后端
软件技术NINI2 小时前
圣罗兰彩妆html+css 4页
前端·css·html
2601_951615202 小时前
网站模板 网站网页模板下载
前端·网络·html
酷炫码神3 小时前
Day 1|HTML5:一个商城首页的骨架,从 DOCTYPE 到语义化
前端·html·html5
AI源码3 小时前
鲜花商城(HTML 版)
前端·html
hiahiahia1233 小时前
Message 和对话
服务器·前端·数据库
溪语流沙4 小时前
【Web全栈进阶】Composition API与组件通信:props深入、emit、插槽
前端·css·vue.js