在Nuxt中使用react-id-swiper封装公共的轮播图组件(移动端

首先就是引入swiper

import Swiper from 'react-id-swiper';
一个轮播图首先要考虑到一种情况就是当只有一张图的时候是不是需要按轮播图来处理
一般情况下,一张图是不需要按轮播图来处理的,只需要放一张图片即可。
对传入的图片地址、是否自动播放、高度进行类型规定
其中url是数据中所带的点击图片要跳转的地址
featureImage为图片的url地址
  static propTypes = {
    data: PropTypes.arrayOf(
      PropTypes.shape({
        url: PropTypes.string,
        featuredImage: PropTypes.string,
      })
    ),
    autoplay: PropTypes.bool,
    height: PropTypes.number,
  }
对轮播图进行配置
 rebuildOnUpdate为banner图片发生改变时是否更新盒子
 height为banner高度
 loop为是否循环轮播,也就是重最后一张可以轮播回第一张
 pagination为配置banner底部的轮播导航,其中el写死,type为底部的样式
  type: 'bullets'为小圆点
   bulletClass: 轮播到这一张图是小圆点的样式
   bulletActiveClass: 没有轮播到这一张图小圆点样式
  autoplay 规定是否自动轮播以及轮播时间
 this.params = {
      rebuildOnUpdate: true,
      height: height,
      loop: true,
      pagination: {
        el: '.swiper-pagination',
        type: 'bullets',
        bulletClass: styles.bulletClass,
        bulletActiveClass: styles.bulletActiveClass,
      },
      autoplay: autoplay ? {delay: 5000, disableOnInteraction: false} : false,
    }

banner所需要的各种数据已经定义好,那么就可以写html骨架了

首先定义单个图片的骨架


对其中的url进行判断,url为点击图片跳转的连接(一般后端返回的数据中会配置
如果有用link将其包裹
window的事件抛发是为了在窗口大小发生改变的时候重新加载图片,使图片立即适应窗口大小
onLoad
class CarouselItem extends Banner { constructor(props) { super(props) } render() {
return ( <React.Fragment key={this.props.index}> {this.props.url ? ( <Link href={this.props.url}> <a style={{display: 'block'}}> <img src={`${this.props.featuredImage}`} onLoad={() => { window.dispatchEvent(new Event('resize')) }} style={{height: this.props.height, width: '100%'}} /> </a> </Link> ) : ( <img src={`${this.props.featuredImage}`} onLoad={() => { window.dispatchEvent(new Event('resize')) }} style={{height: this.props.height, width: '100%'}} /> )} </React.Fragment> ) } }

接下来就是banner整个组件的骨架结构

当只有一张图的时候就只需要将这个图片渲染出来就ok
当超过一张的时候就需要用到Swiper这个轮子,将规定好的配置params放进去就ok了

render() { const {data}
= this.props return ( <div className={styles['uni-banner']}> {data && (data.length == 1 ? ( <CarouselItem {...this.props} {...data[0]} /> ) : ( <Swiper {...this.params}> {data.map((info, index) => ( <div key={index}> <CarouselItem {...this.props} {...info} /> </div> ))} </Swiper> ))} </div> ) }
 
 

猜你喜欢

转载自www.cnblogs.com/ayujun/p/11573990.html