这里只显示关键代码
方法:
componentDidMount(){ // 热门推荐 导航 let galleryThumbs = new window.Swiper('.hot-nav', { slidesPerView : 'auto', observer: true,//修改swiper自己或子元素时,自动初始化swiper observeParents: true,//修改swiper的父元素时,自动初始化swiper watchSlidesVisibility: true, watchSlidesProgress: true, }); this.setState({galleryThumbs:galleryThumbs}); }
setTranslate (index){ const {indexAllProducts} = this.props; const list = !indexAllProducts ? [] : [ ...new Set(indexAllProducts.map(item => item.sellCategoryName))]; let maxIndex = list.length - 1;// 最大索引值 const clientWidth = this.refs.swiperItem.clientWidth; let galleryThumbs = this.state.galleryThumbs; if(galleryThumbs){ if(index < 2){ galleryThumbs.setTranslate(0);//设定位移,tab从0开始 }else if(maxIndex-2 === index || maxIndex-1 === index || maxIndex === index){ galleryThumbs.setTranslate(-clientWidth * (maxIndex-2));//设定位移,tab向左滑动到最后 }else if(index >= 2 || index < maxIndex - 2 ){ galleryThumbs.setTranslate(-clientWidth * (index - 1));//设定位移,tab向左滑动 } } }
标签内容:
<div className="swiper-container hot-nav"> <div className="swiper-wrapper"> <div className={"swiper-slide "} ref='swiperItem' ><span onClick={()=>this.scrollToAnchor("热门推荐")} >热门推荐</span></div> {list.filter(item => item).map((item,index)=>{ return <div key={index} className="swiper-slide " name={index} onClick={()=>this.setTranslate(index)}><span>{item}</span></div>; })} </div> </div>
页面效果:
如遇不妥,欢迎指正.