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

如何在React JS中使用Swiper实现卡片动效轮播?

修复Swiper卡片动效(Effect Cards)不生效的问题

你的代码没触发目标卡片动效,核心是三个配置/路径问题,以下是具体修正方案:

关键修改点

  • 修正模块导入路径:从官方Swiper包导入EffectCards,而非本地自定义路径
  • 添加effect: 'cards'配置:明确指定Swiper使用卡片动效,这是触发3D切换的核心开关
  • 优化布局尺寸:调整容器与幻灯片尺寸,让3D动效有足够展示空间

修正后的完整代码

// 正确导入Swiper官方模块
import { EffectCards } from 'swiper/modules';
import { Swiper, SwiperSlide } from 'swiper/react';

// 导入必要样式
import 'swiper/css';
import 'swiper/css/effect-cards';

const ITEMS = [
  { src: require("./assets/one.jpeg") },
  { src: require("./assets/two.jpeg") },
  { src: require("./assets/three.jpeg") },
  { src: require("./assets/four.jpeg") },
];

const App = () => {
  return (
    <div className="w-screen h-screen bg-slate-900 flex items-center justify-center">
      <Swiper
        modules={[EffectCards]}
        // 核心配置:启用cards动效
        effect="cards"
        // 自定义卡片动效参数,可按需调整
        cardsEffect={{
          rotate: 50,
          scale: 0.7,
        }}
        className="w-[300px] h-[450px]"
      >
        {ITEMS.map((item, index) => (
          <SwiperSlide key={index}>
            <div className="w-full h-full rounded-lg overflow-hidden shadow-2xl">
              <img src={item.src} alt={`slide-${index}`} className="w-full h-full object-cover" />
            </div>
          </SwiperSlide>
        ))}
      </Swiper>
    </div>
  );
};

export default App;

额外优化说明

  • 给SwiperSlide添加key属性,符合React列表渲染规范
  • 给幻灯片添加圆角和阴影,视觉效果更贴近示例图
  • 外层容器用flex布局让轮播居中,提升页面美观度

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 18:05:21