React 中使用 swiper 外掛
安裝 Swiper
npm install --save swiper
編寫 Swiper 元件
1,首先引入 Swiper 以及樣式
// 引入此路徑,才不會打包失敗
import Swiper from 'swiper/dist/js/swiper.js'
import 'swiper/dist/css/swiper.min.css'
2,在元件掛載完畢的時候生成 Swiper 物件
componentDidMount(){
new Swiper('.swiper-container', {
loop: true, //迴圈
autoplay:{ //自動播放,注意:直接給autoplay:true的話,在點選之後不能再自動播放了
delay: 2500,
disableOnInteraction: false, //戶操作swiper之後,是否禁止
},
pagination: {
el: '.swiper-pagination',
clickable: true, // 允許點選跳轉
},
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev',
},
});
}
render() {
const bannerImg = this.props.bannerImg;
return (
<div className="swiper-container">
<div className="swiper-wrapper">
{bannerImg.map((item,index)=>(
<div key={index} className="swiper-slide" style={{backgroundImage:`url(${item})`}}></div>
))}
</div>
<div className='swiper-pagination'></div>
<div className='swiper-button-warp'> // swiper-button-warp是自己加的,為了讓按鈕居中對齊
<div className="swiper-button-next"></div>
<div className="swiper-button-prev"></div>
</div>
</div>
)
}