乐闻世界logo
搜索文章和话题

How to call stopPropagation in reactjs?

1个答案

1

In ReactJS, if you want to prevent event bubbling when handling events, you need to call event.stopPropagation() within the event handler function. This prevents the event from propagating further to parent elements. Here is an example:

jsx
class MyComponent extends React.Component { handleClick = (event) => { // Prevent the event from bubbling up event.stopPropagation(); // Event handling logic console.log('Button clicked!'); } render() { return ( <div onClick={() => console.log('Div clicked!')}> <button onClick={this.handleClick}>Click me</button> </div> ); } }

In this example, when you click the button, the handleClick event handler is triggered. Due to the call to event.stopPropagation() within the handler, the click event does not bubble up to the outer div element, so the onClick handler on the div is not executed. Therefore, when you click the button, you will only see 'Button clicked!' in the console, and not 'Div clicked!'.

For functional components, the code is slightly different:

jsx
function MyComponent() { function handleClick(event) { // Prevent the event from bubbling up event.stopPropagation(); // Event handling logic console.log('Button clicked!'); } return ( <div onClick={() => console.log('Div clicked!')}> <button onClick={handleClick}>Click me</button> </div> ); }

In this example for functional components, the handleClick function works similarly to the method in class components. It also prevents event bubbling to avoid triggering the onClick event on the outer div.

2024年6月29日 12:07 回复

你的答案