网站开发毕业设计书,苏州品牌网站设计企业,网站编辑内容,免费网页空间申请最近项目中需要用到轮播图#xff0c;我立马想起了 swiper #xff0c;那么本文就来带大家体验一下如何在 React 中使用这个插件#xff0c;使用的是 函数组 hooks 的形式。
需求非常简单#xff0c;就是一个可以自动播放、点击切换的轮播图#xff08;跑马灯#xff0…最近项目中需要用到轮播图我立马想起了 swiper 那么本文就来带大家体验一下如何在 React 中使用这个插件使用的是 函数组 hooks 的形式。
需求非常简单就是一个可以自动播放、点击切换的轮播图跑马灯可以同时展示n张图片无限滚动。注意如果是遇到纯文字的轮播效果那我建议完全可以不用这么重的东西直接使用 antd 中的Tab 组件或者干脆自己写也能达到效果
直接食用
示例效果如下
1、安装依赖
npm i swiper2、直接完成代码 需要什么就从swiper/modules中拓展下面的几个满足大多数需求
// index.tsx
import { useState } from react;
import { Navigation, Pagination, Scrollbar } from swiper/modules;
import { Swiper, SwiperSlide } from swiper/react;
import swiper/css;
import swiper/css/navigation;
import swiper/css/pagination;
import swiper/css/scrollbar;import ./index.css
import SlideNextButton from ./SlideNextButton //自定义控制按钮export default function Index () {const [ list ] useState([ 1, 2, 3, 4, 5, 6, 7])return (SwiperloopcenteredSlidesmodules{[Navigation, Pagination, Scrollbar]}spaceBetween{50}slidesPerView{3}navigation // 对应 Navigationpagination{{ clickable: true }} // 对应 Paginationscrollbar{{ draggable: true }} // 对应 ScrollbaronSwiper{(swiper) console.log(swiper)}onSlideChange{() console.log(slide change)}{ list.map(item SwiperSlidediv classNamecard{ item }/div/SwiperSlide)}SlideNextButton//Swiper);
};
// index.css
.card{display: flex;justify-content: center;align-items: center;height: 200px;background: pink;
}额外的自定控制组件 SlideNextButton/ 要使用useSwiper 一定要将组件作为 Swiper/子组件使用
// SlideNextButton.tsx
import { useSwiper } from swiper/react;export default function SlideNextButton() {const swiper useSwiper();const onPrev () {swiper.slidePrev()}const onNext () {swiper.slideNext()}return (div style{{ position: fixed }}button onClick{onPrev}prev/buttonbutton onClick{onNext}next/button/div);
}