You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在React的Swiper组件中设置自动播放5秒后停止?

实现Swiper自动播放5秒后停止(老虎机效果)

要实现自动播放5秒后停止的老虎机效果,你可以通过获取Swiper实例并调用其停止方法结合定时器来完成,具体实现如下:

核心实现逻辑

  1. 用useRef获取Swiper组件的实例,以此调用Swiper的原生API
  2. 组件挂载后,通过setTimeout设置5秒后触发停止自动播放的操作
  3. 组件卸载时清理定时器,避免内存泄漏

修改后的完整代码

import { useRef, useEffect } from 'react';
import 'swiper/css';
import 'swiper/css/pagination';
import { Swiper, SwiperSlide } from 'swiper/react';
import { Autoplay } from "swiper";
import { logos } from './logos';

export const SliderComponent = () => {
  const swiperRef = useRef(null);

  useEffect(() => {
    // 5秒后停止自动播放
    const stopTimer = setTimeout(() => {
      swiperRef.current?.swiper?.autoplay.stop();
    }, 5000);

    // 组件卸载时清除定时器
    return () => clearTimeout(stopTimer);
  }, []);

  return (
    <Swiper
      ref={swiperRef}
      direction={"vertical"}
      className="mySwiper"
      speed={100}
      autoplay={{
        delay: 10,
        disableOnInteraction: false,
      }}
      modules={[Autoplay]}
    >
      {logos.map(logo => (
        <SwiperSlide key={logo.id}>
          <img src={logo.img} alt="logos" className='object-contain w-full' />
        </SwiperSlide>
      ))}
    </Swiper>
  );
};

关键细节说明

  • swiperRef:通过ref绑定到Swiper组件,用于获取底层的Swiper实例对象
  • useEffect钩子:在组件首次渲染完成后启动定时器,时间到后调用autoplay.stop()终止自动播放
  • 定时器清理:返回的清理函数会在组件卸载时清除定时器,防止无效的异步操作残留
  • 语法修正:修复了原代码中SliderComponent的定义错误(=>改为= () =>),并正确包裹了JSX返回内容

内容的提问来源于stack exchange,提问作者Akshay Benny

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 00:10:41