React + swiper 的 banner
import React from 'react'
import Swiper from 'swiper'
const Item = ( props ) => {
return (
<div className="swiper-slide">
<img src = { props.src }/>
</div>
)
}
class Banner extends React.Component{
constructor () {
super()
this.state = {
banners: []
}
}
renderItem = () => {
return this.state.banners.map( ( item ) => {
return <Item { ...item } key = { item.id }></Item>
})
}
render () {
return (
<div className="swiper-container" ref = { el => this.swiper = el}>
<div className="swiper-wrapper" >
{ this.renderItem() }
</div>
<div className="swiper-pagination"></div>
<div className="swiper-button-prev"></div>
<div className="swiper-button-next"></div>
<div className="swiper-scrollbar"></div>
</div>
)
}
componentDidMount () {
fetch ( '/data.json' )
.then( res => res.json() )
.then( data => {
this.setState({
banners: data
})
setTimeout ( () => {
this.swiperObj = new Swiper ( this.swiper, {
loop: true,
pagination: {
el: '.swiper-pagination',
},
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev',
},
scrollbar: {
el: '.swiper-scrollbar',
}
},0)
})
})
.catch( error => {
if( error ) throw error
})
}
componentDidUpdate () {
if( this.swiper ) return false
}
}
export default Banner