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

React中如何让函数结合getElementById变量实现复用?

问题分析与解决方案

你的问题出在事件绑定的写法上:当你写onMouseEnter={mouseOver("discord")}时,这个函数会在页面渲染时立刻执行,而不是等鼠标悬停时才触发。此时事件绑定的是函数执行后的返回值(这里是undefined),所以鼠标悬停时自然没有任何反应。

下面给你两种可行的解决方法:

方法一:用箭头函数包裹,传递ID参数

修改图片的事件绑定代码,把直接调用函数改成箭头函数包裹,这样传递给onMouseEnter的是一个待执行的函数,只有鼠标悬停时才会触发:

<a href="https://discord.gg/N8SDJGSzeS" target="_blank">
  <img className="img imgDiscord" id="discord" src={discord} onMouseEnter={() => mouseOver("discord")} />
</a>

<a href="https://docs.google.com/document/d/15nLun4hYEI3l4Zf9MVMZkigGe9FD4Was5dDZLD3E6E8" target="_blank">
  <img className="img" src={rulesIcon} id="rules" onMouseOver={() => mouseOver("rules")}/>
</a>

你的mouseOver函数可以保持不变:

function mouseOver(ids){
  document.getElementById(ids).style.height = "100px";
}

方法二:利用事件对象获取当前元素(更推荐)

不需要传递ID,直接通过事件对象的target属性拿到触发事件的图片元素,这样函数完全通用,不管多少张图都能复用,还不用依赖ID:

function mouseOver(e) {
  e.target.style.height = "100px";
}

图片的事件绑定改回最初的写法即可:

<a href="https://discord.gg/N8SDJGSzeS" target="_blank">
  <img className="img imgDiscord" id="discord" src={discord} onMouseEnter={mouseOver} />
</a>

<a href="https://docs.google.com/document/d/15nLun4hYEI3l4Zf9MVMZkigGe9FD4Was5dDZLD3E6E8" target="_blank">
  <img className="img" src={rulesIcon} id="rules" onMouseOver={mouseOver}/>
</a>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 13:10:30