本文主要是介绍React Swiper轮播图,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
需求
使用库
- swiper官网 https://swiperjs.com/react
实现方法
/** 组件:图片轮播*/
import React, { Component } from "react";
import SwiperCore, { Navigation, Pagination, Autoplay, Thumbs } from "swiper";
import { Swiper, SwiperSlide } from "swiper/react";
import "swiper/swiper-bundle.css";
import styles from "./index.less";
SwiperCore.use([Navigation, Pagination, Autoplay, Thumbs]);interface IProps {imgs?: Array<any>;
}class Gallery extends Component<IProps, any> {constructor(props) {super(props);this.state = {swiper: null,swiperThumb: null,activeIndex: 0,};}render(): JSX.Element {const { imgs = [] } = this.props;const { activeIndex } = this.state;return (<div className={styles.picsBox}><div className={styles.picsBig}><SwiperautoplaynavigationloopedSlides={5}className={styles.swiperBox}pagination={{type: "fraction",}}thumbs={{ swiper: this.state?.swiperThumb }}onSlideChange={(swiper) => {this.setState({ activeIndex: swiper?.activeIndex });this.state?.swiperThumb.slideTo(swiper?.activeIndex);}}onSwiper={(swiper) => this.setState({ swiper })}>{imgs.map((imgInfo, index) => {return (<SwiperSlide key={index}><img src={imgInfo} className={styles.imgBox} /></SwiperSlide>);})}</Swiper></div><div className={styles.picsList}><SwiperonSwiper={(swiperThumb) => this.setState({ swiperThumb })}className={styles.swiperBoxThumb}spaceBetween={16}slidesPerView={4}freeMode={true}direction={"vertical"}watchSlidesVisibility={true}watchSlidesProgress={true}>{imgs.map((imgInfo, index) => {return (<SwiperSlide key={index} className={styles.swiperBoxThumbSlide}>{activeIndex !== index ? (<div className={styles.mask}></div>) : null}<img src={imgInfo} className={styles.thumbImg} /></SwiperSlide>);})}</Swiper></div></div>);}
}export default Gallery;
.picsBox {width: 100%;height: 650px;display: flex;justify-content: space-between;align-items: center;.picsBig {width: 900px;height: 100%;}.picsList {width: 236px;height: 100%;overflow: hidden;}.imgBox {width: 100%;height: 100%;object-fit: cover;cursor: pointer;}
}.swiperBox {width: 100%;height: 100%;color: white;text-shadow: 1px 1px 10px rgba(0, 0, 0, 0.3);font-size: 16px;--swiper-theme-color: white;
}.swiperBoxThumb {width: 236px;height: 650px;.swiperBoxThumbSlide {position: relative;width: 100%;height: 150px;overflow: hidden;cursor: pointer;}.thumbImg {width: 100%;height: 100%;object-fit: cover;}.mask {position: absolute;left: 0;top: 0;right: 0;bottom: 0;background-color: rgba(255, 255, 255, 0.3);}
}
.swiper-slide-thumb-active {opacity: 1 !important;
}
效果预览
这篇关于React Swiper轮播图的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!