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

React映射元素中如何仅在当前hover项显示隐藏菜单

解决React遍历图片时悬停菜单全局显示的问题

问题出在悬浮菜单的显示判断逻辑上:你当前用isHovered && (...)的判断条件,只要isHovered不是初始值-1,所有遍历出来的图片项都会触发这个条件显示菜单。正确的逻辑应该是只有当前项的索引和状态中存储的isHovered值一致时,才显示对应的悬浮菜单。

修改方式很直接,把菜单的渲染条件改成:

{isHovered === index && (
  <div className='h-full w-full z-90 bg-red-500 absolute top-0 left-0'>
    hi
  </div>
)}

完整修复后的代码:

export default function Collection() {
  const [isHovered, setIsHovered] = useState(-1) 

  return (
    <div className='grid mv:grid-cols-1 md:grid-cols-2 lg:grid-cols-3 px-24 gap-x-16 gap-y-52 place-items-center'>
      {collection.imageData.map((image, index) => {
        return (
          <Link
            href={`/illustrations/${id}/${image.url}`}
            key={index} // 建议如果image有唯一id字段,替换成image.id作为key
            className='relative cursor-pointer h-full flex items-center hover:border hover:border-[#DCDCDC] hover:shadow-lg ease-in duration-150'
            onMouseEnter={() => setIsHovered(index)}
            onMouseLeave={() => setIsHovered(-1)}
          >
            {isHovered === index && (
              <div className='h-full w-full z-90 bg-red-500 absolute top-0 left-0'>
                hi
              </div>
            )}
            <Image
              src={image.image}
              alt={`Vector ${image.alt} illustration`}
            />
            <p className='whitespace-nowrap text-center text-sm px-6 py-2 bg-white text-black border rounded-sm border-black absolute -bottom-24 left-1/2 transform -translate-x-1/2 -translate-y-1/2'>
              Preview image
            </p>
          </Link>
        )
      })}
    </div>
  )
}

额外提示:尽量避免用index作为组件的key,如果你的image数据里有唯一标识(比如image.id),替换成它会让组件渲染更稳定。

内容的提问来源于stack exchange,提问作者maxheezy's

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 16:32:11