本文主要是介绍NextJS开发:使用swiper实现轮播图,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
安装swiper
npm i swiper
创建组件
- 一定要添加"use client",作为客户端组件来使用
- 示例代码中的样式使用的tailwindcss
"use client"
import { Swiper, SwiperSlide } from "swiper/react"
import { Pagination } from 'swiper/modules';// Import Swiper styles
import 'swiper/css';
import 'swiper/css/pagination';
import Image from "next/image"function IndexCarousel() {return (<><Swiper// install Swiper modulesmodules={[Pagination]}spaceBetween={0}slidesPerView={1}pagination={{ clickable: true }}onSlideChange={() => console.log("slide change")}onSwiper={(swiper) => console.log(swiper)}><SwiperSlide className="w-full" style={{ background: "lightblue", height: 300 }}>Slide 1</SwiperSlide><SwiperSlide className="w-full" style={{ background: "lightblue", height: 300 }}>Slide 2</SwiperSlide><SwiperSlide className="w-full" style={{ background: "lightblue", height: 300 }}>Slide 3</SwiperSlide><SwiperSlide className="w-full" style={{ background: "lightblue", height: 300 }}>Slide 4</SwiperSlide></Swiper></>)
}export default IndexCarousel
使用组件
import IndexCarousel from "@/components/index/index-carousel"...return (<><div className="w-full max-w-screen-xl overflow-hidden"><IndexCarousel/></div></>)
使用图片作为轮播图,替换组件代码
return (<><Swiper// install Swiper modulesmodules={[Pagination]}spaceBetween={0}slidesPerView={1}pagination={{ clickable: true }}onSlideChange={() => console.log("slide change")}onSwiper={(swiper) => console.log(swiper)}><SwiperSlide><Image src={"/icon/banner1.jpg"}width={800} height={200} alt={""}className="rounded-md cursor-pointer w-full"/></SwiperSlide><SwiperSlide><Image src={"/icon/banner1.jpg"}width={800} height={200} alt={""}className="rounded-md cursor-pointer w-full"/></SwiperSlide><SwiperSlide><Image src={"/icon/banner1.jpg"}width={800} height={200} alt={""}className="rounded-md cursor-pointer w-full"/></SwiperSlide><SwiperSlide><Image src={"/icon/banner1.jpg"}width={800} height={200} alt={""}className="rounded-md cursor-pointer w-full"/></SwiperSlide></Swiper></>)
这篇关于NextJS开发:使用swiper实现轮播图的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!