Swiper 反应组件

If you are upgrading from Swiper 9 to Swiper 10, check out Migration Guide to Swiper 10
If you are looking for v9 docs, they are here v9.swiperjs.com

安装

¥Installation

Swiper React 仅通过 NPM 提供,作为 Swiper 主库的一部分:

¥Swiper React is available only via NPM as a part of the main Swiper library:

  npm i swiper

用法

¥Usage

swiper/react 导出 2 个组件:SwiperSwiperSlide

¥swiper/react exports 2 components: Swiper and SwiperSlide:

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

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

export default () => {
  return (
    <Swiper
      spaceBetween={50}
      slidesPerView={3}
      onSlideChange={() => console.log('slide change')}
      onSwiper={(swiper) => console.log(swiper)}
    >
      <SwiperSlide>Slide 1</SwiperSlide>
      <SwiperSlide>Slide 2</SwiperSlide>
      <SwiperSlide>Slide 3</SwiperSlide>
      <SwiperSlide>Slide 4</SwiperSlide>
      ...
    </Swiper>
  );
};
By default Swiper React uses core version of Swiper (without any additional modules). If you want to use Navigation, Pagination and other modules, you have to install them first.

以下是从 swiper/modules 导入的附加模块列表:

¥Here is the list of additional modules imports from swiper/modules:

  • Virtual - 虚拟幻灯片模块

    ¥Virtual - Virtual Slides module

  • Keyboard - 键盘控制模块

    ¥Keyboard - Keyboard Control module

  • Mousewheel - 鼠标滚轮控制模块

    ¥Mousewheel - Mousewheel Control module

  • Navigation - 导航模块

    ¥Navigation - Navigation module

  • Pagination - 分页模块

    ¥Pagination - Pagination module

  • Scrollbar - 滚动条模块

    ¥Scrollbar - Scrollbar module

  • Parallax - 视差模块

    ¥Parallax - Parallax module

  • FreeMode - 自由模式模块

    ¥FreeMode - Free Mode module

  • Grid - 网格模块

    ¥Grid - Grid module

  • Manipulation - 幻灯片操作模块(仅适用于核心版本)

    ¥Manipulation - Slides manipulation module (only for Core version)

  • Zoom - 缩放模块

    ¥Zoom - Zoom module

  • Controller - 控制器模块

    ¥Controller - Controller module

  • A11y - 辅助功能模块

    ¥A11y - Accessibility module

  • History - 历史导航模块

    ¥History - History Navigation module

  • HashNavigation - 哈希导航模块

    ¥HashNavigation - Hash Navigation module

  • Autoplay - 自动播放模块

    ¥Autoplay - Autoplay module

  • EffectFade - 淡入淡出效果模块

    ¥EffectFade - Fade Effect module

  • EffectCube - 立方体效果模块

    ¥EffectCube - Cube Effect module

  • EffectFlip - 翻转效果模块

    ¥EffectFlip - Flip Effect module

  • EffectCoverflow - Coverflow 效果模块

    ¥EffectCoverflow - Coverflow Effect module

  • EffectCards - 卡片效果模块

    ¥EffectCards - Cards Effect module

  • EffectCreative - 创意效果模块

    ¥EffectCreative - Creative Effect module

  • Thumbs - 缩略图模块

    ¥Thumbs - Thumbs module

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

import { Swiper, SwiperSlide } from 'swiper/react';

// Import Swiper styles
import 'swiper/css';
import 'swiper/css/navigation';
import 'swiper/css/pagination';
import 'swiper/css/scrollbar';

export default () => {
  return (
    <Swiper
      // install Swiper modules
      modules={[Navigation, Pagination, Scrollbar, A11y]}
      spaceBetween={50}
      slidesPerView={3}
      navigation
      pagination={{ clickable: true }}
      scrollbar={{ draggable: true }}
      onSwiper={(swiper) => console.log(swiper)}
      onSlideChange={() => console.log('slide change')}
    >
      <SwiperSlide>Slide 1</SwiperSlide>
      <SwiperSlide>Slide 2</SwiperSlide>
      <SwiperSlide>Slide 3</SwiperSlide>
      <SwiperSlide>Slide 4</SwiperSlide>
      ...
    </Swiper>
  );
};
Note, Swiper React component will create required elements for Navigation, Pagination and Scrollbar if you pass these params without specifying its elements (e.g. without navigation.nextEl, pagination.el, etc.)

样式

¥Styles

Swiper 包包含不同的 CSS、Less 和 SCSS 样式集:

¥Swiper package contains different sets of CSS, Less and SCSS styles:

  • swiper/css - 仅核心 Swiper 样式

    ¥swiper/css - only core Swiper styles

  • swiper/css/bundle - 所有 Swiper 样式,包括所有模块样式(例如导航、分页等)

    ¥swiper/css/bundle - all Swiper styles including all modules styles (like Navigation, Pagination, etc.)

模块样式(如果已导入 bundle 样式,则无需添加):

¥Modules styles (not required if you already imported bundle styles):

  • swiper/css/a11y - A11y 模块所需样式

    ¥swiper/css/a11y - styles required for A11y module

  • swiper/css/autoplay - 自动播放模块所需样式

    ¥swiper/css/autoplay - styles required for Autoplay module

  • swiper/css/controller - 控制器模块所需样式

    ¥swiper/css/controller - styles required for Controller module

  • swiper/css/effect-cards - 卡片效果模块所需样式

    ¥swiper/css/effect-cards - styles required for Cards Effect module

  • swiper/css/effect-coverflow - Coverflow 效果模块所需样式

    ¥swiper/css/effect-coverflow - styles required for Coverflow Effect module

  • swiper/css/effect-creative - 创意效果模块所需样式

    ¥swiper/css/effect-creative - styles required for Creative Effect module

  • swiper/css/effect-cube - 立方体效果模块所需样式

    ¥swiper/css/effect-cube - styles required for Cube Effect module

  • swiper/css/effect-fade - 所需样式淡入淡出效果模块

    ¥swiper/css/effect-fade - styles required for Fade Effect module

  • swiper/css/effect-flip - 翻转效果模块所需样式

    ¥swiper/css/effect-flip - styles required for Flip Effect module

  • swiper/css/free-mode - 自由模式模块所需样式

    ¥swiper/css/free-mode - styles required for Free Mode module

  • swiper/css/grid - 网格模块所需样式

    ¥swiper/css/grid - styles required for Grid module

  • swiper/css/hash-navigation - 哈希导航模块所需样式

    ¥swiper/css/hash-navigation - styles required for Hash Navigation module

  • swiper/css/history - 历史记录模块所需样式

    ¥swiper/css/history - styles required for History module

  • swiper/css/keyboard - 键盘模块所需样式

    ¥swiper/css/keyboard - styles required for Keyboard module

  • swiper/css/manipulation - 操作模块所需样式

    ¥swiper/css/manipulation - styles required for Manipulation module

  • swiper/css/mousewheel - 鼠标滚轮模块所需样式

    ¥swiper/css/mousewheel - styles required for Mousewheel module

  • swiper/css/navigation - 导航模块所需样式

    ¥swiper/css/navigation - styles required for Navigation module

  • swiper/css/pagination - 分页模块所需样式

    ¥swiper/css/pagination - styles required for Pagination module

  • swiper/css/parallax - 视差模块所需样式

    ¥swiper/css/parallax - styles required for Parallax module

  • swiper/css/scrollbar - 滚动条模块所需样式

    ¥swiper/css/scrollbar - styles required for Scrollbar module

  • swiper/css/thumbs - 缩略图模块所需样式

    ¥swiper/css/thumbs - styles required for Thumbs module

  • swiper/css/virtual - 虚拟模块所需样式

    ¥swiper/css/virtual - styles required for Virtual module

  • swiper/css/zoom - 缩放模块所需样式

    ¥swiper/css/zoom - styles required for Zoom module

对于 Less 样式,请在导入路径中将 css 替换为 less,例如:

¥For Less styles replace css with less in imports paths, e.g.:

import 'swiper/less';
import 'swiper/less/navigation';
import 'swiper/less/pagination';

对于 SCSS 样式,请在导入路径中将 css 替换为 scss,例如:

¥For SCSS styles replace css with scss in imports paths, e.g.:

import 'swiper/scss';
import 'swiper/scss/navigation';
import 'swiper/scss/pagination';

Swiper 属性

¥Swiper props

Swiper React 组件接收所有 Swiper parameters 作为组件属性,以及一些额外的属性:

¥Swiper React component receive all Swiper parameters as component props, plus some extra props:

属性类型默认描述
tagstring'div'主 Swiper 容器 HTML 元素标签
wrapperTagstring'div'Swiper 封装器 HTML 元素标签
onSwiper(swiper) => void'div'接收 Swiper 实例的回调函数

此外,它还支持所有 on{Eventname} 格式的 Swiper events 属性。例如,slideChange 事件变为 onSlideChange 属性:

¥Also it supports all Swiper events in on{Eventname} format. For example slideChange event becomes onSlideChange prop:

  <Swiper
    onSlideChange={() => {/*...*/}}
    onReachEnd={() => {/*...*/}}
    ...
  >

SwiperSlide 属性

¥SwiperSlide props

属性类型默认描述
tagstring'div'Swiper Slide HTML 元素标签
zoombooleanfalse启用缩放模式所需的额外封装器
virtualIndexnumber实际的滑动条索引。虚拟幻灯片需要设置

SwiperSlide 渲染函数

¥SwiperSlide render function

SwiperSlide 组件可以接受 render 函数,该函数接收具有以下属性的对象:

¥SwiperSlide component can accept render function that receives an object with the following properties:

  • isActive - 当前幻灯片为活动幻灯片时为 true

    ¥isActive - true when current slide is active

  • isPrev - 当当前幻灯片是活动幻灯片中的上一张时,为 true

    ¥isPrev - true when current slide is the previous from active

  • isNext - 当当前幻灯片是活动幻灯片中的下一张

    ¥isNext - true when current slide is the next from active

  • isVisible - 当当前幻灯片可见时,为 true(必须启用 watchSlidesProgress Swiper 参数)

    ¥isVisible - true when current slide is visible (watchSlidesProgress Swiper parameter must be enabled)

  • isDuplicate - 当前幻灯片为重复幻灯片时(启用 loop 模式时)例如:

    ¥isDuplicate - true when current slide is a duplicate slide (when loop mode enabled) For example:

<Swiper>
  <SwiperSlide>
    {({ isActive }) => (
      <div>Current slide is {isActive ? 'active' : 'not active'}</div>
    )}
  </SwiperSlide>
</Swiper>

useSwiper

Swiper React 提供 useSwiper 钩子,可轻松获取 Swiper 内部组件中的 Swiper 实例:

¥Swiper React provides useSwiper hook to easliy get the Swiper instance in components inside of Swiper:

// some-inner-component.jsx
import { React } from 'react';
import { useSwiper } from 'swiper/react';

export default function SlideNextButton() {
  const swiper = useSwiper();

  return (
    <button onClick={() => swiper.slideNext()}>Slide to the next slide</button>
  );
}

useSwiperSlide

useSwiperSlide 是 Swiper 幻灯片内部组件获取幻灯片数据(与 SwiperSlide 渲染函数 中的数据相同)的另一个钩子。

¥useSwiperSlide is one more hook for components inside of Swiper slides to get the slide data (same data as in SwiperSlide render function)

// some-inner-component.jsx
import { React } from 'react';
import { useSwiperSlide } from 'swiper/react';

export default function SlideTitle() {
  const swiperSlide = useSwiperSlide();

  return (
    <p>Current slide is {swiperSlide.isActive ? 'active' : 'not active'}</p>
  );
}

插槽

¥Slots

Swiper React 使用 "slots" 进行内容分发。有 4 个可用插槽

¥Swiper React uses "slots" for content distribution. There are 4 slots available

  • container-start - 元素将添加到 swiper-container 的开头

    ¥container-start - element will be added to the beginning of swiper-container

  • container-end(默认) - 元素将添加到 swiper-container 的末尾

    ¥container-end (default) - element will be added to the end of swiper-container

  • wrapper-start - 元素将添加到 swiper-wrapper 的开头

    ¥wrapper-start - element will be added to the beginning of swiper-wrapper

  • wrapper-end - 元素将添加到 swiper-wrapper 的末尾

    ¥wrapper-end - element will be added to the end of swiper-wrapper

例如:

¥For example:

<Swiper>
  <SwiperSlide>Slide 1</SwiperSlide>
  <SwiperSlide>Slide 2</SwiperSlide>
  <span slot="container-start">Container Start</span>
  <span slot="container-end">Container End</span>
  <span slot="wrapper-start">Wrapper Start</span>
  <span slot="wrapper-end">Wrapper End</span>
</Swiper>

将渲染为:

¥Will be rendered as:

<div class="swiper">
  <span slot="container-start">Container Start</span>
  <div class="swiper-wrapper">
    <span slot="wrapper-start">Wrapper Start</span>
    <div class="swiper-slide">Slide 1</div>
    <div class="swiper-slide">Slide 2</div>
    <span slot="wrapper-end">Wrapper End</span>
  </div>
  <span slot="container-end">Container End</span>
</div>

虚拟幻灯片

¥Virtual Slides

此处的虚拟幻灯片渲染完全由 React 处理,除了设置幻灯片的 virtual:true 属性和 virtualIndex 属性外,无需任何其他操作:

¥Virtual Slides rendering here is fully handled by React and not required anything except setting virtual:true property and setting virtualIndex on slides:

import { Virtual } from 'swiper/modules';
import { Swiper, SwiperSlide } from 'swiper/react';

// Import Swiper styles
import 'swiper/css';
import 'swiper/css/virtual';

export default () => {
  // Create array with 1000 slides
  const slides = Array.from({ length: 1000 }).map(
    (el, index) => `Slide ${index + 1}`
  );

  return (
    <Swiper modules={[Virtual]} spaceBetween={50} slidesPerView={3} virtual>
      {slides.map((slideContent, index) => (
        <SwiperSlide key={slideContent} virtualIndex={index}>
          {slideContent}
        </SwiperSlide>
      ))}
    </Swiper>
  );
};

控制器

¥Controller

控制器需要将一个 Swiper 实例传递给另一个 Swiper 实例:

¥Controller requires to pass one Swiper instance to another:

  import React, { useState } from 'react';
  import { Controller } from 'swiper/modules';
  import { Swiper, SwiperSlide } from 'swiper/react';

  const App = () => {
    // store controlled swiper instance
    const [controlledSwiper, setControlledSwiper] = useState(null);

    return (
      <main>
        {/* Main Swiper -> pass controlled swiper instance */}
        <Swiper modules={[Controller]} controller={{ control: controlledSwiper }} ...>
          {/* ... */}
        </Swiper>

        {/* Controlled Swiper -> store swiper instance */}
        <Swiper modules={[Controller]} onSwiper={setControlledSwiper} ...>
          {/* ... */}
        </Swiper>
      </main>
    )
  }

对于双向控制(当两个 Swiper 互相控制时),应该如下所示:

¥For two-way control (when both Swipers control each other) it should be like this:

import React, { useState } from 'react';
import { Controller } from 'swiper/modules';
import { Swiper, SwiperSlide } from 'swiper/react';

const App = () => {
  // store swiper instances
  const [firstSwiper, setFirstSwiper] = useState(null);
  const [secondSwiper, setSecondSwiper] = useState(null);

  return (
    <main>
      <Swiper
        modules={[Controller]}
        onSwiper={setFirstSwiper}
        controller={{ control: secondSwiper }}
      >
        {/* ... */}
      </Swiper>

      <Swiper
        modules={[Controller]}
        onSwiper={setSecondSwiper}
        controller={{ control: firstSwiper }}
      >
        {/* ... */}
      </Swiper>
    </main>
  );
};

缩略图

¥Thumbs

与控制器相同,我们需要存储缩略图实例并将其传递给主图库:

¥Same as with controller we need to store thumbs instance and pass it to main gallery:

  import React, { useState } from 'react';
  import { Swiper, SwiperSlide } from 'swiper/react';
  import { Thumbs } from 'swiper/modules';

  const App = () => {
    // store thumbs swiper instance
    const [thumbsSwiper, setThumbsSwiper] = useState(null);

    return (
      <main>
        {/* Main Swiper -> pass thumbs swiper instance */}
        <Swiper modules={[Thumbs]} thumbs={{ swiper: thumbsSwiper }} ...>
          {/* ... */}
        </Swiper>

        {/* Thumbs Swiper -> store swiper instance */}
        {/* It is also required to set watchSlidesProgress prop */ }
        <Swiper
          modules={[Thumbs]}
          watchSlidesProgress
          onSwiper={setThumbsSwiper}
          ...
        >
          {/* ... */}
        </Swiper>
      </main>
    )
  }

效果

¥Effects

可用效果如下:

¥The following effects are available:

  • 淡入淡出

    ¥Fade

  • 立方体

    ¥Cube

  • Coverflow

  • 翻转

    ¥Flip

  • 卡片

    ¥Cards

  • 创意

    ¥Creative

要使用效果,你必须先导入并安装它们(与所有其他模块一样)。

¥To use effects you have to import and install them first (as all other modules).

你可以找到正在运行的 effect demos here

¥You can find running effect demos here.

完全淡入淡出效果示例

¥Full Fade Effect Example

import React from 'react';
import { Swiper, SwiperSlide } from 'swiper/react';
import { EffectFade } from 'swiper/modules';

import 'swiper/css';
import 'swiper/css/effect-fade';

export default () => {
  return (
    <Swiper modules={[EffectFade]} effect="fade">
      {[1, 2, 3].map((i, el) => {
        return <SwiperSlide>Slide {el}</SwiperSlide>;
      })}
    </Swiper>
  );
};

与 Create React App 一起使用

¥Usage with Create React App

Create React App 尚不支持纯 ESM 包。仍然可以在 Swiper (7.2.0+) 中使用。

¥Create React App doesn't support pure ESM packages yet. It is still possible to use Swiper (7.2.0+) with it.

在这种情况下,我们需要使用直接文件导入:

¥In this case we need to use direct file imports:

// Core modules imports are same as usual
import { Navigation, Pagination } from 'swiper/modules';
// Direct React component imports
import { Swiper, SwiperSlide } from 'swiper/swiper-react.mjs';

// Styles must use direct files imports
import 'swiper/swiper.scss'; // core Swiper
import 'swiper/modules/navigation.scss'; // Navigation module
import 'swiper/modules/pagination.scss'; // Pagination module

下一步?

¥What next?

正如你所见,将 Swiper 集成到你的网站或应用中非常容易。接下来的步骤如下:

¥As you see it is really easy to integrate Swiper into your website or app. So here are your next steps: