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

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

// 轮播图的业务逻辑
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);
  }
               // 轮播图的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>

你可能感兴趣的:(react,native,react,native,javascript,前端)