React-native 入坑4 无限轮播图

无限轮播图可以说是实际在项目中用到的最多的组件,之间做过的项目一般在首页都会有无限轮播的存在。
主要思路

1. index 0 插入最后数组的最后一张图片
2. index array.count+ 1 插入第一张图片
3.中间顺序放入数组中的元素
4.当滑动到index 0 的位置时,将scrollview 的偏移数组的最后一张所在的位置
5.当滑动到index array.count+ 1 的位置时,将偏移量置为数组第一张的位置

逻辑想通了,接下来就是代码的实现了。作为一个入坑react native的人来说,把几个关键点想通就可以了。

1.这个肯定得考虑复用性,那么得封装成一个单独的组件,组件怎么实现通信呢?

props

constructor(props){
       super(props);
    }

const imageUrls = this.props.imageUrls;

传值:

import ViewPager from './component/viewpage'
const imageUrls = ['https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=760528960,2729756840&fm=26&gp=0.jpg', 
     'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1558514797592&di=b7404ddc598d9e395f33f36ef883ebf4&imgtype=0&src=http%3A%2F%2Fc4.haibao.cn%2Fimg%2F600_0_100_0%2F1530690356.3493%2F81eaeb56a5255d33fdb280712f3b252d.jpg',
      'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1558514797592&di=4fc04bc668b9a3ec1e1e75208aeb4b43&imgtype=0&src=http%3A%2F%2Fgss0.baidu.com%2F7Po3dSag_xI4khGko9WTAnF6hhy%2Fzhidao%2Fpic%2Fitem%2F4b90f603738da977a600eedebb51f8198618e31c.jpg'];

这就是一个简单的传值

2.怎么布局?

可以先去官网看看scrollview 的相关属性以及函数,这里我们需要用到他的结束拖拽的函数
onMomentumScrollEnd
因为需要监听scrollview的偏移量。
因为布局相关的代码比较多,这里的思路就是将image用一个单独的函数去render,然后在scrollview中用for循环去嵌套。

_renderPagerItem(url ,key){
        console.log('render item complete');
        return(
            
            
            
        )
    }

render image

按之前说过的插入顺序进行插入:

 _renderPager(){
        const imageUrls = this.props.imageUrls;
        if(imageUrls == null || imageUrls.length == 0){
            return null
        }
        let count = imageUrls.length
        let pagers = []
        if(count == 1){
            pagers.push(this._renderPagerItem(imageUrls[0],0))
        }else{
            //将最后一张插入到index为0 的位置
            pagers.push(this._renderPagerItem(imageUrls[count -1],0))
            //依次插入
            for(let i = 0 ; i< count; i++){
                pagers.push(this._renderPagerItem(imageUrls[i],i+1))
            }
            //将第一张插入到最后一个位置
            pagers.push(this._renderPagerItem(imageUrls[0],count + 1))
        }
        console.log('render pagers complete')
        return pagers

    }
3.最后有个很小的点就是,关于公用布局代码的问题,之前我一直不知道怎么弄:其实就是用一个数组包含两个布局的css样式就可以了
const styles = StyleSheet.create({
   test1:{
     width: 100,
     height:30,
   },
   test2:{
     backgroundColor: 'red'
   }
 })
使用:
 

下面是运行的效果图:


React-native 入坑4 无限轮播图_第1张图片
image.png

暂时还没加入定时器,所以未实现自动轮播。刚刚入坑,希望自己的一点心得能帮助到其他人。
demo地址

你可能感兴趣的:(React-native 入坑4 无限轮播图)