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

React中如何在断点处隐藏和显示Swiper导航?

React + Tailwind + Swiper 导航隐藏后失效的解决方案

问题描述

我用Tailwind样式搭建了React Typescript的Swiper轮播组件,原本功能正常,但调整窗口大小隐藏导航后,再次显示导航时就失效了。我是通过Tailwind的hidden类来隐藏导航的,请问在React中如何正确在不同断点下隐藏/显示Swiper导航?

原代码

import { Navigation, Pagination } from 'swiper';
import { Swiper, SwiperSlide } from "swiper/react";
import 'swiper/css';
import 'swiper/css/navigation';

const Slider = ({slides}) => {
  const prevRef = useRef<HTMLButtonElement>(null);
  const nextRef = useRef<HTMLButtonElement>(null);

  return (
    <div>
      <Swiper
        slidesPerView={'auto'}
        spaceBetween={16}
        className='custom-swiper-slide'
        navigation={{
          enabled: true,
          nextEl: nextRef.current,
          prevEl: prevRef.current,
          disabledClass: 'opacity-40',
        }}
        breakpoints={{
          320: {
            slidesPerView: 'auto',
            spaceBetween: 8,
            //navigation: {enabled: false} - not working!
            //navigation: {hidden: true} - not working!
          },
          640: {
            slidesPerView: 1,
            spaceBetween: 16,
          }
        }}
        onBeforeInit={(swiper) => {
          if (swiper.params.navigation && typeof swiper.params.navigation !== 'boolean') {
            swiper.params.navigation.prevEl = prevRef.current;
            swiper.params.navigation.nextEl = nextRef.current;
          }
        }}
        modules={[Navigation]}
      >
        {slides.map((slide) => {
          return (
            <SwiperSlide>
             ...slide...
            </SwiperSlide>
          )})
        }
      </Swiper>
      <div className='hidden md:block'> {/* show/hide nav buttons */}
        {/* After the buttons have been hidden once, they stop working, they appear but don't work */}
        <button ref={prevRef}>prev</button>
        <button ref={nextRef}>next</button>
      </div>
    </div>
  );
}

解决方案

问题根源

用Tailwind的hidden类隐藏按钮时,元素会被设置为display: none,Swiper初始化时绑定的事件监听会因为元素状态变更失效;原断点配置里的navigation设置无效是因为层级结构不对,需要在断点内完整配置navigation对象。

修正步骤

  1. 同步Swiper断点与Tailwind断点的导航状态
    在Swiper的breakpoints中正确配置navigation.enabled,让Swiper在断点切换时自动启用/禁用导航,同时配合Tailwind控制按钮显示。

  2. 简化Swiper配置
    移除冗余的onBeforeInit代码,Swiper React组件会自动处理ref与导航元素的绑定。

修改后的代码

import { Navigation } from 'swiper';
import { Swiper, SwiperSlide } from "swiper/react";
import 'swiper/css';
import 'swiper/css/navigation';
import { useRef } from 'react';

const Slider = ({ slides }) => {
  const prevRef = useRef<HTMLButtonElement>(null);
  const nextRef = useRef<HTMLButtonElement>(null);

  return (
    <div>
      <Swiper
        slidesPerView={'auto'}
        spaceBetween={16}
        className='custom-swiper-slide'
        // 默认启用导航(对应md及以上断点)
        navigation={{
          enabled: true,
          prevEl: prevRef.current,
          nextEl: nextRef.current,
          disabledClass: 'opacity-40',
        }}
        breakpoints={{
          // 320px及以下断点:禁用导航
          320: {
            slidesPerView: 'auto',
            spaceBetween: 8,
            navigation: { enabled: false }
          },
          // 640px及以上断点:启用导航(与默认保持一致)
          640: {
            slidesPerView: 1,
            spaceBetween: 16,
            navigation: { enabled: true }
          }
        }}
        modules={[Navigation]}
      >
        {slides.map((slide, index) => (
          <SwiperSlide key={index}>
            {slide}
          </SwiperSlide>
        ))}
      </Swiper>
      {/* 用Tailwind控制按钮显示,与Swiper断点同步 */}
      <div className='hidden md:flex gap-2 mt-4'>
        <button ref={prevRef} className='px-4 py-2 bg-gray-100'>prev</button>
        <button ref={nextRef} className='px-4 py-2 bg-gray-100'>next</button>
      </div>
    </div>
  );
};

export default Slider;

额外说明

  • 当窗口尺寸切换时,Swiper会自动根据断点配置更新导航状态,重新绑定事件,避免按钮显示后失效的问题。
  • 确保Tailwind的断点(如md:)与Swiper的breakpoints值对应,保持视觉与功能的同步。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 06:09:59