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

React中如何获取映射生成元素的rect.top与rect.left值?

解决方法

你报错的核心原因是把循环的**index(数字类型)**当成DOM元素调用getBoundingClientRect(),数字本身没有这个方法,自然会触发类型错误。下面是两种正确获取当前悬停卡片位置的方式:

方法一:通过事件对象直接获取当前元素

在map渲染卡片时,给每个卡片绑定鼠标事件,从事件对象的currentTarget属性拿到当前悬停的DOM元素:

// 渲染卡片列表
{cards.map((card, index) => (
  <div 
    key={index} 
    className="card"
    onMouseMove={(e) => handleGlow(e)}
    onMouseLeave={() => resetGlow()}
  >
    {/* 卡片内容 */}
  </div>
))}

// 处理鼠标移动逻辑
const handleGlow = (e) => {
  // 获取当前卡片的位置信息
  const cardRect = e.currentTarget.getBoundingClientRect();
  const cardTop = cardRect.top;
  const cardLeft = cardRect.left;
  
  // 结合鼠标在卡片内的偏移计算光泽层位置
  const mouseXInCard = e.clientX - cardLeft;
  const mouseYInCard = e.clientY - cardTop;
  // 这里可以用计算出的数值设置光泽层的transform或定位样式
};

方法二:用ref数组存储卡片元素

先创建ref数组保存每个卡片的DOM引用,再通过index获取对应元素的位置信息:

import { useRef } from 'react';

// 初始化ref数组
const cardRefs = useRef([]);

// 渲染卡片列表
{cards.map((card, index) => (
  <div 
    key={index} 
    className="card"
    ref={el => cardRefs.current[index] = el}
    onMouseEnter={() => handleCardHover(index)}
    onMouseMove={(e) => handleCardHover(index, e)}
  >
    {/* 卡片内容 */}
  </div>
))}

// 处理悬停逻辑
const handleCardHover = (index, e) => {
  const cardEl = cardRefs.current[index];
  if (!cardEl) return;
  
  const cardRect = cardEl.getBoundingClientRect();
  const cardTop = cardRect.top;
  const cardLeft = cardRect.left;
  
  // 后续光泽层位置计算逻辑
};

两种方法中,方法一更简洁直接,无需额外维护ref数组;如果需要在其他场景也访问卡片DOM元素,方法二更灵活。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 16:25:21