在react中使用swiper/react

2,157 阅读1分钟

参考链接:swiper6.vercel.app/react#usage

其实swiper中文文档很多api都是直接阔以用的,只是形式不一样

中文文档:www.swiper.com.cn/api/

安装:yarn add swiper@6

import { Swiper, SwiperSlide } from 'swiper/react'
import { sliderList } from './source'
import SwiperCore, { Pagination, Autoplay, Navigation } from 'swiper'
import styled from '@emotion/styled'

// Import Swiper styles
import 'swiper/swiper-bundle.css'
import { useEffect, useState } from 'react'

export const MaskingLeft = styled.div`
  left: ${(props) => `${-props.offset}px`};
`

export const MaskingRight = styled.div`
  right: ${(props) => `${-props.offset}px`};
`

// 另外加载其他附加模块,比如 Navigation、Pagination 等模块
SwiperCore.use([Pagination, Autoplay, Navigation])

const ITEM_WIDTH = 1200
const MARGIN_RIGHT = 48

export const SwiperHome = () => {
  const [offset, setOffset] = useState(ITEM_WIDTH)
  
  const pagination = {
    "clickable": true,
    "renderBullet": function (index, className) {
            return '<span class=\"' + className + '\"><span class="user-defined"></span></span>';
          }
  }
  
  // 自定义前进后退按钮navigation   需要加.
  const navigation = { prevEl: '.masking-left', nextEl: '.masking-right' }
  
  return (
    <div className='swiper__content'>
      <MaskingLeft className='masking-left' offset={offset} />
      <MaskingRight className='masking-right' offset={offset} />
      <Swiper
        allowTouchMove={false}
        autoplay={{
          delay: 8000,
          disableOnInteraction: false,
        }}
        centeredSlides={true}
        initialSlide={1}
        loop={true}
        navigation={navigation}
        pagination={pagination}
        slideToClickedSlide={true}
        slidesPerView="auto"
        spaceBetween={48}
        speed={700}
        onSwiper={(swiper) => {
          console.log(swiper, "onSwiper")
        }}
      >
        {sliderList.map((item, index) => {
          return (
            <SwiperSlide key={index}>
              <div className="slider-item-left">
                <img alt="" className="item-left_icon" src={item.icon} />
                <div className="item-left_title">{item.title}</div>
                <div className="item-left_title">{item.titleTwo}</div>
                <div className="item-left_text">{item.text}</div>
              </div>
              <div className="slider-item-right">
                <img alt="" className="item-left_icon" src={item.img} />
              </div>
            </SwiperSlide>
          )
        })}
      </Swiper>
    </div>
  )
}