關於swiper動態更改,無法更新的悖論


關於swiper動態更改,無法更新的悖論

以前都覺得swiper的使用很簡單,那是因為使用swiper時都是寫的數據,按照官網上介紹直接初始化swiper,隨便丟一個地方初始化就ok了,但是在很多需求中,我們都需要動態的改變數據,這樣可能就會遇到很多問題。

最近在react搭建環境中,使用swiper就遇上一些問題:

1. 初始化后,在react的鈎子里面new 出來的swiper對象作用域問題。
2. 更改swiper,更新時很多方法不能使用。
3. 修改數據swiper里面的slider出現混亂。
4. 數據不匹配(需要加載的數據以改變,但是swiper里面的數據出現錯誤)。

``` class Banner extends Component { static defaultProps = { imageData:['image/b1.jpg','image/b2.jpg','image/b3.jpg','image/b4.jpg','image/b5.jpg','image/b6.jpg','image/b7.jpg','image/b8.jpg'], imgData:['img/1.jpg','img/2.jpg','img/3.jpg','img/4.jpg','img/5.jpg','img/6.jpg','img/7.jpg','img/8.jpg','img/9.jpg','img/10.jpg','img/11.jpg'] }
componentDidMount() {
	this.mySwiper = new Swiper('.Banner', {
      pagination: {
        el: '.swiper-pagination',
      },
      autoplay: {
      	delay: 3000,
	    stopOnLastSlide: false,
	    disableOnInteraction: true,
      },
      loop:true,
      effect : 'fade',
    });
}

componentWillReceiveProps() {
	console.log(1111);
	this.mySwiper.update();
}

render() {
	var sliderFn = (arr) => {
		var sliderArr = [];
		for(var i=0; i<arr.length; i++) {
			sliderArr.push(<div class="swiper-slide"><img src={arr[i]}/>'</div>)
		}
		return sliderArr;
	}
	
	return (
		<div class="swiper-container Banner">
		    <div class="swiper-wrapper">
		    	{sliderFn(this.props.imgFlag ? this.props.imgData : this.props.imageData)}
		    </div>
		    <div class="swiper-pagination"></div>
		</div>
	)
}

}

<p>
真正的核心部分在
</p>
<p>
observer:true,//修改swiper自己或子元素時,自動初始化swiper </p>
<p>observeParents:false,//修改swiper的父元素時,自動初始化swiper </p>

onSlideChangeEnd: function(swiper){
   swiper.update();
   mySwiper.startAutoplay();
   mySwiper.reLoop();
}

 

<p>加上這串代碼后,使用基本正常</p>

<p>mySwiper.reLoop(); 重新對需要循環的slide個數進行計算,當你改變了slidesPerView參數時需要用到,需要自動輪播的時候必須要加上;</p>

<p>swiper.update();  更新Swiper,這個方法包含了updateContainerSize,updateSlidesSize,updateProgress,updatePagination,updateClasses方法。也就是數據改變是重新初始化一次swiper;</p>

<p>mySwiper.startAutoplay(); 重新開始自動切換;</p>

<p>但是還會有一個問題,比如說在初始化頁面是,初始化加載一組數據,但是這組數據里面只有一條信息,但是其他組數據里面包含了多條信息,在這種情況下必須要手動切換一次才能觸發自動輪播,還沒找到解決辦法。</p>

<p>
以上就是遇到的一些問題,記錄一下,以后遇到還可以看看。
</p>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM