废话不多说,直接上代码(由于功能比较简单就没必要简述了)
// 轮播图的业务逻辑
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 && (<ScrollViewref={ref => {this.scrollViewRef = ref}}horizontalpagingEnabledshowsHorizontalScrollIndicator={false}>{this.state.list.map((item, index) => (<Imagekey={index}source={{ uri: item.path }}style={styles.itemImage}/>))}</ScrollView>)}</View>