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

react-image-lightbox多组图片独立预览 点击始终加载最后一组图片问题求解

问题原因

  • 缺失激活项目标识状态:仅用isOpen控制灯箱显隐、photoIndex记录当前图片索引,没有存储用户点击的是哪一组项目,灯箱打开后无法匹配对应图片列表。
  • 多灯箱渲染冲突:你在Projects.map循环内为每个项目都单独渲染了Lightbox组件,所有组件共用同一个isOpen状态,当isOpen为true时所有项目的Lightbox都会同时渲染,位于DOM结构最后的最后一组项目的Lightbox会覆盖前面的,导致你永远看到最后一组的图片。

修复方案

  1. 新增存储当前激活项目索引的状态,点击图片时同时记录点击的项目索引、重置图片索引、打开灯箱
  2. 将Lightbox组件从map循环中移出,全局只渲染一个Lightbox,通过激活的项目索引匹配对应图片组

修改后代码示例

首先修改状态定义:

// 原有状态保留,新增激活项目索引状态
const [isOpen, setIsOpen] = useState(false);
const [photoIndex, setPhotoIndex] = useState(0);
const [activeProjectIndex, setActiveProjectIndex] = useState(0);

然后修改渲染逻辑:

{Projects.map(function(project, index) {
  return (
    <Image 
      onClick={() => {
        setActiveProjectIndex(index);
        setPhotoIndex(0); // 每次打开新组默认从第一张开始预览
        setIsOpen(true);
      }} 
      loading="lazy" 
      className="rounded-img img-project shadow-three" 
      src={project.images[0]} 
    />
  )
})}
{/* Lightbox 移到map外部,全局只渲染一个 */}
{isOpen && (
  const currentProject = Projects[activeProjectIndex];
  <Lightbox
    imageLoadErrorMessage="This image failed to load"
    imageTitle={currentProject.name}
    mainSrc={currentProject.images[photoIndex]}
    nextSrc={currentProject.images[(photoIndex + 1) % currentProject.images.length]}
    prevSrc={
      currentProject.images[
        (photoIndex + currentProject.images.length - 1) % currentProject.images.length
      ]
    }
    onCloseRequest={() => setIsOpen(false)}
    onMovePrevRequest={() =>
      setPhotoIndex(
        (photoIndex + currentProject.images.length - 1) % currentProject.images.length
      )
    }
    onMoveNextRequest={() =>
      setPhotoIndex((photoIndex + 1) % currentProject.images.length)
    }
  />
)}

内容的提问来源于stack exchange,提问作者Deybi Tabora Paz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 04:06:02