gpt4 book ai didi

reactjs - React 将事件绑定(bind)到许多 dom 元素的有效方法

转载 作者:行者123 更新时间:2023-12-03 13:29:48 26 4
gpt4 key购买 nike

因为我们直接将 onClick 处理程序添加到组件中...例如:

<button onClick={dosomething}>Click</button>

当我们处理数十个元素时,是否有一种有效的方法来做到这一点(不是向每个元素添加 onClick)?

例如,在我的主干应用程序中,我只需将处理程序应用于类:

events:
'click .someclass': 'doSomething'

Backbone 方式看起来更干净、更容易管理。有没有办法用 React Components 来模拟这种行为?

为了添加一些观点,我说了十几个或更多表单元素,当它们中的任何一个发生更改时,我希望可能运行一些逻辑。它们可以是文本框、单选按钮等。

最佳答案

不需要此优化。如果您在 jQuery 之类的其他库中进行编码,那么会发生这种情况,但 React 会自动为您完成此操作。

我引用:

Event delegation: React doesn't actually attach event handlers to the nodes themselves. When React starts up, it starts listening for all events at the top level using a single event listener. When a component is mounted or unmounted, the event handlers are simply added or removed from an internal mapping. When an event occurs, React knows how to dispatch it using this mapping. When there are no event handlers left in the mapping, React's event handlers are simple no-ops. To learn more about why this is fast, see David Walsh's excellent blog post.

在这里看到:https://facebook.github.io/react/docs/interactivity-and-dynamic-uis.html

关于reactjs - React 将事件绑定(bind)到许多 dom 元素的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30400276/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com