安装swiper
npm i swiper
创建组件
- 一定要添加"use client",作为客户端组件来使用
- 示例代码中的样式使用的tailwindcss
"use client"
import { Swiper, SwiperSlide } from "swiper/react"
import { Pagination, Autoplay } from 'swiper/modules'
// Import Swiper styles
import 'swiper/css';
import 'swiper/css/pagination';
import Image from "next/image"
function IndexCarousel() {
return (
<>
<Swiper
// install Swiper modules
modules={[Pagination]}
spaceBetween={0}
slidesPerView={1}
autoplay={true}
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 modules
modules={[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>
</>
)
网友评论