如何在 React 中操作 swiper.js 的幻灯片数组?

How to manipulate slide array of swiper.js in React?

我正在尝试向我的滑块添加更多幻灯片。我正在使用 swiper.js and React to do this. I found that sandbox from the official documentation,它应该显示如何在滑块数组中添加或删除幻灯片。但是,沙箱坏了,我无法让它工作。我在最后一个小时尝试了工作,但收效甚微。

我很高兴得到任何提示!

https://codesandbox.io/s/xtosg?file=/src/App.jsx

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

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

import "./styles.css";


// import Swiper core and required modules
import SwiperCore, {
  Pagination,Navigation
} from 'swiper';

// install Swiper modules
SwiperCore.use([Pagination,Navigation]);


export default function App() {
  
  
  
  const [swiperRef, setSwiperRef] = useState(null);

  let appendNumber = 4;
  let prependNumber = 1;

  const prepend2 = () => {
    swiperRef.prependSlide([
      '<div class="swiper-slide">Slide ' + (--prependNumber) + '</div>',
      '<div class="swiper-slide">Slide ' + (--prependNumber) + '</div>'
    ]);
  }

  const prepend = () => {
    swiperRef.prependSlide('<div class="swiper-slide">Slide ' + (--prependNumber) + '</div>');
  }

  const append = () => {
    swiperRef.appendSlide('<div class="swiper-slide">Slide ' + (++appendNumber) + '</div>');
  }

  const append2 = () => {
    swiperRef.appendSlide([
      '<div class="swiper-slide">Slide ' + (++appendNumber) + '</div>',
      '<div class="swiper-slide">Slide ' + (++appendNumber) + '</div>'
    ]);
  }
  
  return (
    <>
    
  <Swiper onSwiper={setSwiperRef} slidesPerView={3} centeredSlides={true} spaceBetween={30} pagination={{
  "type": "fraction"
}} navigation={true} className="mySwiper">
    <SwiperSlide>Slide 1</SwiperSlide>
    <SwiperSlide>Slide 2</SwiperSlide>
    <SwiperSlide>Slide 3</SwiperSlide>
    <SwiperSlide>Slide 4</SwiperSlide>
  </Swiper>

  <p className="append-buttons">
  

  
  
  <button onClick={() => prepend2()} className="prepend-2-slides">Prepend 2 Slides</button>
  <button onClick={() => prepend()} className="prepend-slide">Prepend Slide</button>
  <button onClick={() => append()} className="append-slide">Append Slide</button>
  <button onClick={() => append2()} className="append-2-slides">Append 2 Slides</button>
  </p>
  
    </>
  )
}

参见 Demo。 您必须使用模块 Manipulation 来操作幻灯片 check docs

import SwiperCore, { Pagination, Navigation, Manipulation } from "swiper"; SwiperCore.use([Pagination, Navigation, Manipulation]);