react 中使用 swiper

最近项目中需要用到轮播图,我立马想起了 swiper ,那么本文就来带大家体验一下如何在 React 中使用这个插件,使用的是 函数组 + hooks 的形式。

需求非常简单,就是一个可以自动播放、点击切换的轮播图(跑马灯),可以同时展示n张图片,无限滚动。注意:如果是遇到纯文字的轮播效果,那我建议完全可以不用这么重的东西,直接使用 antd 中的Tab 组件或者干脆自己写也能达到效果
在这里插入图片描述

直接食用

示例效果如下
请添加图片描述

1、安装依赖

npm i swiper

2、直接完成代码
需要什么就从'swiper/modules'中拓展,下面的几个满足大多数需求

// index.tsx
import { useState } from 'react';
import { Navigation, Pagination, Scrollbar } from 'swiper/modules';
import { Swiper, SwiperSlide } from 'swiper/react';
import 'swiper/css';
import 'swiper/css/navigation';
import 'swiper/css/pagination';
import 'swiper/css/scrollbar';

import './index.css'
import SlideNextButton from './SlideNextButton' //自定义控制按钮

export default function Index () => {
  const [ list ] = useState([ 1, 2, 3, 4, 5, 6, 7])

  return (
    <Swiper
      loop
      centeredSlides
      modules={[Navigation, Pagination, Scrollbar]}
      spaceBetween={50}
      slidesPerView={3}
      navigation // 对应 Navigation
      pagination={{ clickable: true }} // 对应 Pagination
      scrollbar={{ draggable: true }} // 对应 Scrollbar
      onSwiper={(swiper) => console.log(swiper)}
      onSlideChange={() => console.log('slide change')}
    >
      { list.map(item =>
        <SwiperSlide>
          <div className="card">
            { item }
          </div>
        </SwiperSlide>
      )}
      <SlideNextButton/>
    </Swiper>
  );
};

// index.css
.card{
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
  background: pink;
}

额外的自定控制组件 <SlideNextButton/>
要使用useSwiper 一定要将组件作为 <Swiper/>子组件使用

// SlideNextButton.tsx
import { useSwiper } from 'swiper/react';

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

  const onPrev = () => {
    swiper.slidePrev()
  }
  
  const onNext = () => {
    swiper.slideNext()
  }

  return (
    <div style={{ position: 'fixed' }}>
      <button onClick={onPrev}>prev</button>
      <button onClick={onNext}>next</button>
    </div>
  );
}

相关推荐

  1. vueswiper使用

    2024-06-06 18:06:03       31 阅读
  2. React使用WebRTC

    2024-06-06 18:06:03       41 阅读
  3. React 使用 TS

    2024-06-06 18:06:03       14 阅读
  4. reactzustand的使用

    2024-06-06 18:06:03       18 阅读
  5. React使用antDesign框架

    2024-06-06 18:06:03       17 阅读
  6. React useReducer的使用

    2024-06-06 18:06:03       18 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-06-06 18:06:03       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-06-06 18:06:03       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-06-06 18:06:03       19 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-06-06 18:06:03       20 阅读

热门阅读

  1. 糖尿病相关的数据集

    2024-06-06 18:06:03       11 阅读
  2. ActiViz中的纹理映射

    2024-06-06 18:06:03       9 阅读
  3. 搭建python环境以及pip

    2024-06-06 18:06:03       9 阅读
  4. 什么是CSTP测试认证,如何通过CSTP认证?

    2024-06-06 18:06:03       7 阅读
  5. 全文检索&ElasticSearch简介

    2024-06-06 18:06:03       8 阅读