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

Posted

技术标签:

【中文标题】如何在 React 中操作 swiper.js 的幻灯片数组?【英文标题】:How to manipulate slide array of swiper.js in React? 【发布时间】:2021-12-06 11:59:49 【问题描述】:

我正在尝试向我的滑块添加其他幻灯片。我正在使用swiper.js 和 React 来执行此操作。我发现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>
  
    </>
  )

【问题讨论】:

【参考方案1】:

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

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

【讨论】:

以上是关于如何在 React 中操作 swiper.js 的幻灯片数组?的主要内容,如果未能解决你的问题,请参考以下文章

Swiper V7 React,很多参数不起作用

swiper.js和jQ啥区别,啥关系,

如何在 Nuxt.js 中使用官方 Swiper.js 作为插件

如何在 swiper.js 中更改滑动方向?

swiper.js我给swiper-slide里面的div设置高度后为啥

swiper.js我给swiper-slide里面的div设置高度后为啥