React OnMouseOut事件不触发 鼠标离开后文本颜色无法重置问题求解
问题根因
- 第一是方法名拼写不匹配:你在JSX的
onMouseOut事件中绑定的方法名为resetBackround,但实际定义的重置方法名为resetBackground,缺少了字母g,导致鼠标移出时无法触发正确的重置逻辑。 - 第二是类组件自定义方法存在
this指向隐患:如果后续方法中需要用到this调用组件属性或状态,未绑定的普通方法会出现this指向异常的问题。
解决方案
快速修复现有代码
- 修正JSX中所有
onMouseOut的绑定方法名,将resetBackround统一改为resetBackground - 建议将事件处理方法改为箭头函数,规避
this指向问题,修改后代码如下:
constructor(props) { super(props); this.state = {}; } // 改为箭头函数 changeBackground = (e) => { e.target.style.color = 'red'; } resetBackground = (e) => { e.target.style.color = 'white'; } handleClick(target) { if (this.props.onClick) { let name; let id; let index = -1; if (target.search("::") > -1) { const varCount = target.split("::").length; if (varCount === 2) { name = target.split("::")[0]; id = target.split("::")[1]; } else if (varCount === 3) { name = target.split("::")[0]; index = parseInt(target.split("::")[1]); id = target.split("::")[2]; } } else { name = target; } this.props.onClick({ type: 'button', name: name, index: index, id: id }); } }
更简洁的CSS实现方案(推荐)
不需要编写任何JS事件逻辑,直接用CSS伪类+过渡属性实现悬停变色和淡入淡出效果,性能更优、代码更易维护:
- 删除所有
div上绑定的onMouseOver和onMouseOut事件属性 - 在全局样式或对应组件样式文件中添加如下CSS代码:
.contact, .classwork, .home { color: white; /* transition属性控制颜色变化的过渡动画,0.3s为动画时长,可自行调整 */ transition: color 0.3s ease; } /* 悬停时的样式 */ .contact:hover, .classwork:hover, .home:hover { color: red; }
内容的提问来源于stack exchange,提问作者goatherder13
相关产品推荐
相关产品推荐

