在React中使用Swiper做触摸内容滑动
缘由
在实现一个触摸内容滑动的功能的时候,想reactJS该怎么处理呢,然后被提点用Swiper可以,一想确实可以。。。。用了网上的一些用在react里面的Swiper,但是并不怎么靠谱和好用。最后看博客,觉得说得很好,原生可以解决所有问题- 0 -,于是去官网看来一下文档,果然原生克一切。
实现以及心得
心得:官方文档一般是最详细也是最清楚的。
附上Swiper的API地址:https://www.swiper.com.cn/api/index.html
使用方法
npm install swiper
import Swiper from 'swiper/dist/js/swiper.js';
import 'swiper/dist/css/swiper.min.css';
- 在componentDidMount创建一个Swiper(有一些注意事项和代码注释,写在代码下面了)
componentDidMount() {
var that = this;
that.getDate(that.state.pramcurrent);//
new Swiper('.swiper-container', {
observer: true,
on: {
reachEnd: function () {
if(that.state.current<that.state.total-2){
that.setState({pramcurrent:that.state.pramcurrent+1})//
that.getDate(that.state.pramcurrent);//
that.setState();//
}
},
slideChangeTransitionEnd: function () {
that.setState({ current: this.activeIndex + 1 });//
},
}
});
}
Tip:
1.Swiper中的参数,第一个是不用变的,第二个的话,需要什么功能就去API里面查,并且添加就好了,这个代码里面主要是用了一个监视器observer,改变Swiper状态的时候自动初始化swiper,方便分页请求,滑动到最后一页再加载两页。on里面是写事件的,这里用了两个,一个是检测到滑动到最后一页的事件reachEnd,用来做动态加载,一个是slideChangeTransitionEnd,切换结束后执行的事件,这个主要是用来做下面的页面显示。当前在多少页,因为是动态加载,所以官方提供的分页器不太好用。
2.一定要在开始的时候,var that=this;不然在事件中调用this.state.xxxx会报错。
render() {
const bannerImg = this.state.totalSwiper;
var bannerImgRender = (
bannerImg.map((item, index) => (
<div key={index} className="swiper-slide">
<div className="sbjs2">
<img src={item} className='sb2'></img>
//中间可以写各种代码,都可以滑动。仅仅只能放图片。
</div>
</div>
))
);
return (
<div className="swiper-container">
<div className="swiper-wrapper">
{bannerImgRender}
</div>
</div>
<div className='fy'>{this.state.current} / {this.state.total} </div>
</div>
);
}
tip:
1.这样子写,不仅仅就滑动图片,组件也可以滑动。直接用map遍历数据,就可以每次滑动的时候改变数据,数据写在state里面。然后可以动态读取接口的数据。
总结
大概框架就是这样的,下次要用的话直接复制过去就可以啦。