在swiper-react中实现滑块联动:滑动一个滑块切换另一个滑块数据
React 中用 swiper-react 实现滑块联动方案
核心思路
监听第一个Swiper的onSlideChange事件,获取当前激活slide对应的ID,触发第二个API请求,更新第二个Swiper的数据源。
实现步骤及代码示例
1. 安装依赖
确保已安装必要包:
npm install swiper swiper-react
2. 完整组件代码
import { useState, useEffect, useRef } from 'react'; import { Swiper, SwiperSlide } from 'swiper/react'; import 'swiper/css'; import 'swiper/css/navigation'; import { Navigation } from 'swiper/modules'; const LinkedSwipers = () => { // 状态管理 const [firstSliderData, setFirstSliderData] = useState([]); const [secondSliderData, setSecondSliderData] = useState([]); const [currentActiveId, setCurrentActiveId] = useState(null); const firstSwiperRef = useRef(null); // 初始化第一个滑块数据 useEffect(() => { const fetchFirstData = async () => { try { // 替换为你的第一个API地址 const res = await fetch('https://api.example.com/first-data'); const data = await res.json(); setFirstSliderData(data); // 默认选中第一个项的ID if (data.length > 0) setCurrentActiveId(data[0].id); } catch (err) { console.error('获取第一个滑块数据失败:', err); } }; fetchFirstData(); }, []); // 当激活ID变化时,请求第二个滑块数据 useEffect(() => { if (!currentActiveId) return; const fetchSecondData = async () => { try { // 替换为你的第二个API地址,传入currentActiveId const res = await fetch(`https://api.example.com/second-data/${currentActiveId}`); const data = await res.json(); setSecondSliderData(data); } catch (err) { console.error('获取第二个滑块数据失败:', err); } }; fetchSecondData(); }, [currentActiveId]); // 处理第一个滑块的滑动切换事件 const handleFirstSlideChange = () => { const swiperInstance = firstSwiperRef.current?.swiper; if (!swiperInstance) return; // 获取当前激活slide的索引,对应firstSliderData中的项 const activeIndex = swiperInstance.activeIndex; const activeItem = firstSliderData[activeIndex]; if (activeItem?.id !== currentActiveId) { setCurrentActiveId(activeItem.id); } }; return ( <div style={{ padding: '20px' }}> <h3>第一个滑块(数据源切换)</h3> <Swiper ref={firstSwiperRef} modules={[Navigation]} slidesPerView={3} spaceBetween={20} navigation onSlideChange={handleFirstSlideChange} initialSlide={0} > {firstSliderData.map(item => ( <SwiperSlide key={item.id} style={{ padding: '10px', border: '1px solid #ddd', borderRadius: '8px' }}> <p>{item.name}</p> </SwiperSlide> ))} </Swiper> <h3 style={{ marginTop: '40px' }}>第二个滑块(联动数据)</h3> <Swiper modules={[Navigation]} slidesPerView={2} spaceBetween={20} navigation > {secondSliderData.map(item => ( <SwiperSlide key={item.id} style={{ padding: '10px', border: '1px solid #ddd', borderRadius: '8px' }}> <p>{item.detail}</p> </SwiperSlide> ))} </Swiper> </div> ); }; export default LinkedSwipers;
常见问题排查(针对你之前onSlideChange失败的情况)
- 没有正确获取Swiper实例:通过
useRef绑定第一个Swiper,确保能拿到真实的swiper实例,避免直接操作DOM导致的错误。 - 状态更新时机错误:在
onSlideChange中要先判断当前激活项的ID是否和已有状态一致,避免重复触发API请求。 - API请求未绑定正确依赖:第二个
useEffect的依赖数组必须包含currentActiveId,确保ID变化时重新请求数据。 - Swiper模块未正确导入:比如
Navigation模块需要手动导入并添加到modules配置中,否则导航按钮等功能会失效,也可能影响事件监听。
内容的提问来源于stack exchange,提问作者Steven
相关产品推荐
相关产品推荐

