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

React Gallery组件路径匹配显示对应图片组问题求助

路径匹配实现Gallery组件动态显示对应图片组

已实现点击项目跳转至对应路径(如example.com/gallery/project%201),Gallery组件中定义了photos和photos2两组图片资源,需求是根据当前路径名匹配projects数组中的项目name,仅显示对应图片组(如匹配project 1时显示photos,隐藏photos2),但多次尝试未成功。

解决方案

实现步骤

  • 解析路径中的项目名称:用decodeURIComponent解码路径中的编码字符,提取完整项目名称。
  • 建立项目与图片组的映射:创建对象关联项目名称和对应图片数组,方便快速匹配。
  • 动态渲染对应图片组:根据匹配结果,只渲染当前项目对应的图片组。

修改后的Gallery组件代码

import { useLocation } from 'react-router-dom';
import { useState, useRef } from 'react';
import projects from './projects';
import { Swiper, SwiperSlide } from 'swiper/react';
import { Navigation } from 'swiper/modules';
import GalleryStyle from './GalleryStyle';

export default function Gallery() {
  const [projectsData] = useState(projects);
  
  const location = useLocation();
  const swiperNavPrevRef = useRef();
  const swiperNavNextRef = useRef();

  // 项目名称与对应图片组的映射
  const projectPhotosMap = {
    'project 1': ['archfosil.jpeg', 'MVI_1419.MP4'],
    'project 2': ['IMG_0753.MOV'],
    // 新增项目时直接扩展此对象即可
  };

  // 提取并解码当前路径中的项目名称
  const pathSegments = location.pathname.split('/');
  const encodedProjectName = pathSegments[pathSegments.length - 1];
  const currentProjectName = decodeURIComponent(encodedProjectName);

  // 获取当前项目对应的图片组,默认空数组避免报错
  const currentPhotos = projectPhotosMap[currentProjectName] || [];

  return (
    <>
      <GalleryStyle>
        <div className="galleryitems">
          <Swiper
            modules={[Navigation]}
            navigation={{
              prevEl: swiperNavPrevRef.current,
              nextEl: swiperNavNextRef.current,
            }}
            style={{ "--swiper-theme-color": "#fff" }}
            speed={800}
            slidesPerView={1}
            loop
            className="myswiper"
          >
            <div className="swiperNavPrev" ref={swiperNavPrevRef}></div>
            <div className="swiperNavNext" ref={swiperNavNextRef}></div>
            {currentPhotos.map((photo, i) => (
              <SwiperSlide key={i} className="swiperslide">
                <img src={require(`../assets/images/${photo.toString()}`)} alt={`${currentProjectName} 展示图 ${i+1}`} />
              </SwiperSlide>
            ))}
          </Swiper>
        </div>
      </GalleryStyle>
    </>
  );
}

关键说明

  • projectPhotosMap统一管理项目与图片组的对应关系,后续新增项目无需修改渲染逻辑,只需扩展该对象。
  • 通过拆分路径并解码,确保能正确匹配projects数组中的原始项目名称。
  • 仅渲染匹配到的图片组,完全满足按需显示的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 03:31:03