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

React实现hover显示文本功能时单个div悬停触发全部显示问题求助

问题原因

你当前的两个div共享了同一个text状态变量,所有p标签的透明度都绑定了这个值,任意一个div触发悬停修改状态,两个div的文本都会同步生效,自然会同时显示。

解决方案

方案1:拆分独立状态(适合少量固定div场景)

直接给每个div分配单独的状态变量即可:

// 两个独立状态分别控制对应div的文本显隐
const [text1, setText1] = useState(0);
const [text2, setText2] = useState(0);

<div onMouseEnter={e=> setText1(1)} onMouseLeave={e=> setText1(0)}>
    <h1>hover the div to show the text</h1>
    <p style={{opacity: text1}}>some dummy text</p>
</div>
<div onMouseEnter={e=> setText2(1)} onMouseLeave={e=> setText2(0)}>
    <h1>hover the div to show the text</h1>
    <p style={{opacity: text2}}>some dummy text</p>
</div>

方案2:用状态存储当前悬停的div标识(适合动态生成多div场景)

如果div是动态遍历生成的,就给每个div加唯一标识,状态只存当前激活的标识,匹配时才显示文本:

// 初始值设为null表示没有悬停的div
const [hoverId, setHoverId] = useState(null);

<div 
  onMouseEnter={e=> setHoverId('div1')} 
  onMouseLeave={e=> setHoverId(null)}
>
    <h1>hover the div to show the text</h1>
    <p style={{opacity: hoverId === 'div1' ? 1 : 0}}>some dummy text</p>
</div>
<div 
  onMouseEnter={e=> setHoverId('div2')} 
  onMouseLeave={e=> setHoverId(null)}
>
    <h1>hover the div to show the text</h1>
    <p style={{opacity: hoverId === 'div2' ? 1 : 0}}>some dummy text</p>
</div>

方案3:纯CSS实现(无额外JS状态开销,简单场景优先用)

如果只是单纯的悬停显隐文本,不需要额外JS逻辑的话,直接用CSS伪类实现更简洁:

/* 给div加自定义类名hover-container */
.hover-container p {
  opacity: 0;
  transition: opacity 0.2s; /* 可选添加过渡效果 */
}
.hover-container:hover p {
  opacity: 1;
}

JSX里只需要给div加类名即可,不需要写任何悬停事件和状态:

<div className="hover-container">
    <h1>hover the div to show the text</h1>
    <p>some dummy text</p>
</div>
<div className="hover-container">
    <h1>hover the div to show the text</h1>
    <p>some dummy text</p>
</div>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 20:54:02