Dre*_*cho 3 autoplay reactjs swiper.js
我正在尝试通过构建一个具有自动播放功能的简单图像滑块来学习 swiper.js,但我不知道如何在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;
Run Code Online (Sandbox Code Playgroud)
编辑:
我尝试过类似 onMouseEnter={() => Swiper.autoplay.stop()} onMouseLeave={() => Swiper.autoplay.start()} 但如果我使用类似的东西,它不会奇怪地工作: onClick= {() => Swiper.autoplay.stop()} 它有效......
小智 8
在撰写本文时,React 的 Swiper 似乎尚未实现onMouseEnter、onMouseLeave等。
为了解决这个问题,我将 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>
)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6947 次 |
| 最近记录: |