NextJS开发:使用swiper实现轮播图

安装swiper

npm i swiper

创建组件

  1. 一定要添加"use client",作为客户端组件来使用
  2. 示例代码中的样式使用的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 modules
        modules={[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 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>
    </>
  )

你可能感兴趣的:(NextJS开发教程,NextJS,reactjs)