简体   繁体   中英

React: Adding an event listener to each child and passing down a reference to parent's event handler - is it inefficient? Is event bubbling possible?

I'm new to React and am thinking of applying it to my project for more easily enforceable structure and easy DOM rendering, but I have an issue with event delegation.

In ordinary JS, if you have a container element with an indefinite number of children (eg <button> s), you would just put one event listener on the parent and let the event bubble up. I haven't been able to find examples of doing this with react elements, and not sure if the only way to handle events for this system is by delegating event listeners to all children, which I don't like the sound of.

Can you do event bubbling in React (and access the React element target)?

Could it be the case that when react compiles it compiles into JS that uses event listeners and event bubbling in the 'ordinary' way?

React uses event delegation by default. When you put an onClick on a React component, it doesn't set up a handler on that component's top-level DOM element; uses one on the root component or document instead. The only place I can find this mentioned in the documentation is here where, when talking about dispatching events to your components for testing purposes, it says:

...Note that you need to pass { bubbles: true } in each event you create [for testing] for it to reach the React listener because React automatically delegates events to the document.

It's also mentioned in a comment on this issue :

React doesn't attach your click event handlers to the nodes. It uses event delegation and listens at the document level.

So go ahead and do what seems right for the code you're writing. React will use event delegation under the covers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM