做一个基于ReactJS的轮播图组件
class SwiperCompoent extends React.Component {
swiperId="";
word="";
titleImg="";
constructor(props) {
super(props);
this.state = {
slides: props.exImg,
word:""
}
this.word=props.exWord[0];
this.titleImg=props.exHeader;
this.swiperId=props.exId;
}
componentDidMount() {
this.initSwiper();
}
initSwiper(){
const swiper = new Swiper('#'+this.swiperId, {
initialSlide: 0,
slidesPerView: 1,
freeMode: false,
normalizeSlideIndex: true,
stopOnLastSlide: true,
speed: 300,
spaceBetween: 40,
pagination: '.swiper-pagination',
paginationClickable: true,
onSlideChangeEnd: (swiper) => {
this.word=this.props.exWord[swiper.activeIndex];
/* 这里使用的是 非直接state的渲染模式
利用setState的重新渲染机制
当使用setState重新渲染组件时 将会把this.word的改变值 重新渲染上去
当然也可以 使用this.state.word 直接渲染 */
this.setState({
word:""
});
},
onTouchMove: (swiper, e) => {},
onClickNext: (swiper, e) => {}
});
}
render() {
return (
<div className="swiper">
<div>
<img className="swiper-header" src={this.titleImg} />
</div>
<div className="swiper-piper">
<div className="swiper-container" id={this.swiperId}>
<div className="swiper-wrapper">
{this.state.slides.map((slide, index) => (
<div className="swiper-slide">
<img src={slide} className="swiper-img" />
</div>
))}
</div>
<div class="swiper-pagination"></div>
</div>
<div className="swiper-text">
{this.word}
</div>
</div>
</div>
)
}
}
使用
class Index extends React.Component {
constructor(props) {
super(props);
}
imgData1 = ["1.jpg","2.jpg","3.jpg"];
word1 = ["1", "2", "3"];
componentDidMount() {};
render() {
return (
<div className="main">
<SwiperCompoent exId="exid1" exImg={this.imgData1} exWord={this.word1} exHeader={img_reg}>
</SwiperCompoent>
</div>
);
}
}
网友评论