简体   繁体   中英

React how to add Card element in Swiper slider by onClick event?

反应如何通过 onClick 事件在 Swiper 滑块中添加卡片元素?

I have created Code Sandbox Demo For Adding Card when they are clickDEMO

Below is the code, give it a try. In this Demo the slide will be added to the end so you would need to slide to the end to check the new slide added.

import { useState } from "react";
// Import Swiper React components
import { Swiper, SwiperSlide } from "swiper/react";

// Import Swiper styles
import "swiper/css";

export default function App() {
  const [swipers, setSwipers] = useState([
    "Slide 1",
    "Slide 2",
    "Slide 3",
    "Slide 4"
  ]);

  const addSwiper = (swiper) => {
    setSwipers((prevSwipers) => prevSwipers.concat(swiper));
  };

  return (
    <>
      <Swiper
        spaceBetween={50}
        slidesPerView={3}
        onSlideChange={() => console.log("slide change")}
        onSwiper={(swiper) => console.log(swiper)}
      >
        {swipers.map((swiper, index) => (
          <SwiperSlide key={index}>{swiper}</SwiperSlide>
        ))}
      </Swiper>
      <br />
      <br />
      <br />
      <button onClick={() => addSwiper("Add Swiper Card 1")}>
        Add Swiper Card 1 (Click on this to Add)
      </button>{" "}
      <br />
      <button onClick={() => addSwiper("Add Swiper Card 2")}>
        Add Swiper Card 2 (Click on this to Add)
      </button>
    </>
  );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM