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

React中Swiper响应式断点失效,移动端无法显示2个幻灯片

React Swiper响应式断点失效,移动端无法显示2个幻灯片的解决方法

你的问题核心是开启了centeredSlides={true},这个配置会让Swiper将单个幻灯片居中展示,即使设置了slidesPerView={2},也会因为居中逻辑导致移动端看起来只能显示1个(或不完整的)幻灯片,而非预期的2个。

解决步骤:

  1. 关闭居中模式
    将centeredSlides={true}改为centeredSlides={false},让Swiper按照slidesPerView的设置平铺展示幻灯片。

  2. 修复图片与容器样式
    确保幻灯片内的图片不会超出容器,添加以下样式(全局CSS或组件样式文件中):

    .my-contributions-swiper {
      width: 100%;
    }
    .img-div {
      width: 100%;
    }
    .img-div img {
      width: 100%;
      height: auto;
      display: block;
    }
    
  3. 确认父容器无宽度限制
    确保App.jsx中的外层div没有设置固定宽度,让Swiper容器能自适应移动端屏幕宽度,保证响应式断点正常触发。

修改后的完整组件代码:

import img1 from "../images/swiper-img1.webp";
import img2 from "../images/swiper-img2.webp";
import { Swiper, SwiperSlide } from "swiper/react";
import "swiper/css";
import "swiper/css/pagination";
import { Autoplay, Pagination } from "swiper/modules";

const SwiperSlider = () => {
  return (
    <>
      <Swiper
        slidesPerView={2}
        spaceBetween={10}
        centeredSlides={false}
        loop={true}
        speed={1500}
        autoplay={{
          delay: 500,
          disableOnInteraction: false,
        }}
        pagination={{
          clickable: true,
        }}
        modules={[Autoplay, Pagination]}
        breakpoints={{
          640: {
            slidesPerView: 3,
            spaceBetween: 20,
          },
          768: {
            slidesPerView: 4,
            spaceBetween: 25,
          },
          981: {
            slidesPerView: 5,
            spaceBetween: 30,
          },
        }}
        className="my-contributions-swiper"
      >
        <SwiperSlide>
          <div className="img-div">
            <img src={img1} alt="slide 1" />
          </div>
        </SwiperSlide>
        <SwiperSlide>
          <div className="img-div">
            <img src={img2} alt="slide 2" />
          </div>
        </SwiperSlide>
        <SwiperSlide>
          <div className="img-div">
            <img src={img1} alt="slide 3" />
          </div>
        </SwiperSlide>
        <SwiperSlide>
          <div className="img-div">
            <img src={img2} alt="slide 4" />
          </div>
        </SwiperSlide>
        <SwiperSlide>
          <div className="img-div">
            <img src={img1} alt="slide 5" />
          </div>
        </SwiperSlide>
        <SwiperSlide>
          <div className="img-div">
            <img src={img2} alt="slide 6" />
          </div>
        </SwiperSlide>
      </Swiper>
    </>
  );
};

export default SwiperSlider;

补充说明:

  • 关闭居中模式后,Swiper会严格按照slidesPerView的数值在容器内排列幻灯片,移动端就能正常显示2个完整的幻灯片。
  • 图片设置100%宽度是为了保证幻灯片内容撑满自身容器,避免因图片尺寸问题导致布局错乱。
  • 确保Swiper容器宽度为100%,才能让响应式断点根据屏幕宽度正确切换配置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 03:02:36