Raect中的Swiper js如何在MouseEnter上停止自动播放并在MouseLeave上启动它

IT技术 reactjs swiper autoplay
2021-04-30 06:03:06

我正在尝试通过构建一个带有自动播放功能的简单图像滑块来学习 swiper.js 的react,但我不知道如何在MouseEnter 上停止自动播放并在MouseLeave 上启动它。我试过 onMouseLeave={Swiper.autoplay.stop} 并没有奏效。

import React from 'react';
import classes from './HeroSlider.module.css';
import { Swiper, SwiperSlide } from 'swiper/react';
import SwiperCore, { Navigation, Pagination, Autoplay } from 'swiper';
import 'swiper/swiper-bundle.css'; // swiper.min.css
import image1 from '../../Images/image1.png';
import image2 from '../../Images/image2.png';
import image3 from '../../../Images/image3.png';

SwiperCore.use([ Navigation, Pagination, Autoplay ]);

const HeroSlider = () => {
  return (
    <Swiper 
      className={ classes.MainSlider }
      autoplay={{ delay: 5000, disableOnInteraction: false, reverseDirection: true, waitForTransition: true }}
      pagination={{ clickable: true }}
      navigation
      onMouseEnter={}
      onMouseLeave={}
    >
      <SwiperSlide className="full-w-h-container" tag="li" style={{ listStyle: "none" }}>
        <img className={ `full-w-h-container ${ classes.ImgBg }` } src={image1} alt="image1" />
      </SwiperSlide>
      <SwiperSlide className="full-w-h-container" tag="li" style={{ listStyle: "none" }}>
        <img className={ `full-w-h-container ${ classes.ImgBg }` } src={image2} alt="image2" />
      </SwiperSlide>
      <SwiperSlide className="full-w-h-container" tag="li" style={{ listStyle: "none" }}>
        <img className={ `full-w-h-container ${ classes.ImgBg }` } src={image3} alt="image3" />
      </SwiperSlide>
    </Swiper>
  )
}
export default HeroSlider;

编辑:

我尝试了类似 onMouseEnter={() => Swiper.autoplay.stop()} onMouseLeave={() => Swiper.autoplay.start()} 的东西,但如果我使用类似的东西,它不会奇怪地工作:onClick= {() => Swiper.autoplay.stop()} 它有效......

2个回答

在写这篇的时候,它看起来像组队,探索的阵营并没有实现onMouseEnteronMouseLeave等等。

为了解决这个问题,我将我的 Swiper 组件包装在另一个 React 组件中,并使用这样的引用来引用 Swiper:

import React, { useRef } from 'react'
import { Swiper, SwiperSlide } from 'swiper/react'
import SwiperCore, { Autoplay, Pagination } from 'swiper'
// ...

SwiperCore.use([Autoplay, Pagination])

export default function Slider() {
  const swiperRef = useRef(null)

  return (
    <div 
      onMouseEnter={() => swiperRef.current.swiper.autoplay.stop()}
      onMouseLeave={() => swiperRef.current.swiper.autoplay.start()}
    >
      <Swiper
        ref={swiperRef}
        autoplay={{ delay: 5000 }}
        speed={1300}
        spaceBetween={50}
        slidesPerView={1}
        allowTouchMove={false}
        pagination={{ clickable: true }}
      >
        {/* slides */}
      </Swiper>
    </div>
  )
}

您还可以使用pauseOnMouseEnter: true

autoplay={{
 delay: 3000,
 disableOnInteraction: false,
 pauseOnMouseEnter: true,
}}