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

React中基于条件调用stopPropagation失效的问题求助

Fixing Event.stopPropagation() Not Working in Your React Component

The main issue here is that you're not passing the event object (e) to your handleClick function from the onClick handler. Let's break down what's wrong and how to fix it:

Root Cause

In your JSX, the onClick handler is defined as:

onClick={() => this.handleClick(value.evenTime)}

This arrow function only passes value.evenTime to handleClick, but not the event object. So when your else block runs, e is undefined, and calling e.stopPropagation() has no effect (it might even throw an error in the console).

Corrected Code

First, update the onClick handler to pass the event object:

<div className="event-class" onClick={(e) => this.handleClick(value.evenTime, e)}>
  <div className="o-percentage">Hellloo</div>
</div>

Then, you can keep your handleClick function as is, but adding a check for e is a good practice to avoid potential errors:

handleClick(eventDate, e) {
  if (this.props.eventType === 'DayEvent') {
    this.props.onBarClick(eventDate);
  } else {
    console.log(e, 'e');
    // Ensure the event object exists before calling stopPropagation
    if (e) {
      e.stopPropagation();
    }
  }
}

Why This Works

By passing the e parameter from the onClick arrow function to handleClick, you now have access to the actual browser event object. Calling e.stopPropagation() will correctly prevent the event from bubbling up to parent elements.

Quick Additional Check

Make sure there are no other event handlers on parent elements using event.stopImmediatePropagation() (which blocks all subsequent handlers on the same element), but this isn't the issue in your current code.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:05:05