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

React自定义Square组件onMouseEnter不生效 如何让Board统一处理hover事件

问题根因

给自定义组件Square传入的onMouseEnter本质只是一个普通的props属性,React不会自动将自定义组件上的事件属性绑定到组件内部渲染的真实DOM节点。
你之前的点击事件能正常生效,是因为你在Square的render逻辑里,手动把this.props.onClick绑定到了内部button元素的onClick事件上,onMouseEnter没有做这层透传,自然不会触发。

具体实现

只需要做两层修改,就能实现Board统一管理悬停逻辑:

  • Board层正常定义悬停处理方法,给Square组件传入对应的鼠标进入、离开事件props
  • Square组件内部把父组件传入的事件props,手动绑定到内部渲染的button元素的对应事件上

修改后的代码参考:

Board组件渲染Square部分

return (
  <Square
    src={pieceStr}
    key={pieceStr}
    onMouseEnter={() => this.handleHover(x, y)}
    onMouseLeave={() => this.handleHoverOut(x, y)} // 鼠标移出方格的处理逻辑
    onClick={() => this.handleClick(x, y)}
    className={classes}
  />
);

Square组件render部分

return (
  <button
    onDragOver={(e) => this.onDragOver(e)}
    className={this.props.className}
    onClick={() => this.props.onClick()}
    {/* 透传父组件传入的鼠标事件 */}
    onMouseEnter={this.props.onMouseEnter}
    onMouseLeave={this.props.onMouseLeave}
  >
    {img}
  </button>
);

补充提示:做棋盘悬停效果优先用onMouseEnter/onMouseLeave,这两个事件不会冒泡,鼠标移动到方格内的棋子图片上时不会重复触发事件,比onMouseOver/onMouseOut体验更稳定。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 13:51:27