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

Swiper.js Grid布局断点切换异常:窗口缩小后行数变1,刷新恢复

Swiper Grid布局断点切换异常问题修复

问题情况

使用以下Swiper配置时,窗口尺寸缩小到992px以下(断点阈值),Grid布局的行数会自动变成1行,但刷新页面后又能恢复正常的2行布局:

<Swiper
    grid={{
      rows: 2,
    }}
    spaceBetween={30}
    pagination={{
      clickable: true,
    }}
    modules={[Grid, Pagination]}
    breakpoints={{
      0:{
        slidesPerView: 2,
      },
      576: {
        slidesPerView: 2,
      },
      992: {
        slidesPerView: 3,
      }
    }}
    className="mySwiper"
  >

布局表现细节

  • 屏幕1440px(≥992px):正常显示2行3列布局
  • 窗口缩小至<992px:异常显示1行2列布局
  • 刷新页面后:恢复为正常的2行2列布局

修复方案

问题出在Swiper断点切换时,Grid模块的rows配置没有被正确继承,默认被重置为1行。最可靠的解决方式是在每个断点配置中显式指定rows: 2,确保断点切换时保持Grid行数:

<Swiper
    grid={{
      rows: 2,
    }}
    spaceBetween={30}
    pagination={{
      clickable: true,
    }}
    modules={[Grid, Pagination]}
    breakpoints={{
      0:{
        slidesPerView: 2,
        grid: { rows: 2 }
      },
      576: {
        slidesPerView: 2,
        grid: { rows: 2 }
      },
      992: {
        slidesPerView: 3,
        grid: { rows: 2 }
      }
    }}
    className="mySwiper"
  >

如果不想重复配置,也可以通过监听窗口resize事件,手动触发Swiper的布局更新:

import { useSwiper } from 'swiper/react';
import { useEffect } from 'react';

// 在组件内部添加以下逻辑
const swiper = useSwiper();
useEffect(() => {
  const handleResize = () => swiper.update();
  window.addEventListener('resize', handleResize);
  return () => window.removeEventListener('resize', handleResize);
}, [swiper]);

优先推荐第一种显式配置断点行数的方案,更贴合Swiper的配置规范,无需额外的事件监听开销。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 04:05:01