React中基于条件调用stopPropagation失效的问题求助
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

