简体   繁体   English

反应:为每个孩子添加一个事件侦听器并将一个引用传递给父母的事件处理程序 - 效率低吗? 事件冒泡可能吗?

[英]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.我是 React 新手,正在考虑将它应用到我的项目中,以获得更容易执行的结构和更容易的 DOM 渲染,但我遇到了事件委托的问题。

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.在普通的 JS 中,如果你有一个包含不定数量的子元素的容器元素(例如<button> s),你只需在父元素上放置一个事件监听器并让事件冒泡。 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.我无法找到使用 react 元素执行此操作的示例,并且不确定处理该系统事件的唯一方法是否是将事件侦听器委派给所有子级,我不喜欢这样的声音。

Can you do event bubbling in React (and access the React element target)?你可以在 React 中进行事件冒泡(并访问 React 元素目标)吗?

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 编译时它编译成 JS,它以“普通”方式使用事件侦听器和事件冒泡?

React uses event delegation by default. React 默认使用事件委托。 When you put an onClick on a React component, it doesn't set up a handler on that component's top-level DOM element;当您将onClick放在 React 组件上时,它不会在该组件的顶级 DOM 元素上设置处理程序; uses one on the root component or document instead.在根组件或document上使用一个。 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. ...请注意,您需要在创建 [用于测试] 的每个事件中传递{ bubbles: true }以使其到达 React 侦听器,因为 React 会自动将事件委托给文档。

It's also mentioned in a comment on this issue :对此问题的评论中也提到了这一点:

React doesn't attach your click event handlers to the nodes. React 不会将您的单击事件处理程序附加到节点。 It uses event delegation and listens at the document level.它使用事件委托并在文档级别进行侦听。

So go ahead and do what seems right for the code you're writing.所以 go 提前做你正在编写的代码看起来正确的事情。 React will use event delegation under the covers. React 将在幕后使用事件委托。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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