首先就是引入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> ) }