我看到了一些其他帖子,但不明白。
如果我有一个大表格,每行都有一个可点击的操作按钮。
<tbody>
<tr>
<td><button onClick={this.handleClick}></button></td>
</tr>
</tbody>
在 jquery 中,我会将事件绑定(bind)到 <tbody>
元素,据我所知它有更好的性能。在react中,如果我将点击事件直接绑定(bind)到按钮,实际上会创建多少个处理程序?它会像事件委托(delegate)一样高效吗?
我尝试在 <tbody>
上使用 onClick当我在控制台中访问事件对象时,我看到此警告:
Warning: This synthetic event is reused for performance reasons. If you're seeing this, you're accessing the property `altKey` on a released/nullified synthetic event. This is set to null. If you must keep the original synthetic event around, use event.persist().
最佳答案
我认为有 3 个不同的问题。
- 是否可以使用委托(delegate)?是的,您可以在
<tbody>
上设置单个事件处理程序并检查event.currentTarget.<some attribute to know what it is>
. 为什么会显示警告?这是因为事件对象实际上是被重用的,所以如果你的处理程序以异步方式使用事件,就像
handleClick(event) { setTimeout(() => { alert(event.target.id); }, 100); }
您无法确定这是同一事件。您应该立即存储所需的信息并稍后使用
handleClick(event) { let id_to_store = event.target.id; setTimeout(() => { alert(id_to_store); }, 100); }
- 为什么 React 希望我们设置显式事件处理程序而不是使用委托(delegate)?授权不是更有效率吗?并不真地。一旦你不这样做create new handler function for each element它的开销真的很小。但作为显式绑定(bind)处理程序的优势,您不必担心内存泄漏,因为处理程序被委托(delegate)给生命周期足够长的太常见的父元素。这是唯一的原因吗?不,处理程序集也明确适合“虚拟 DOM 与真实 DOM 比较”。
因此,您可以使用委托(delegate),但最好不要使用委托(delegate),直到出现真正的瓶颈。
关于javascript - React 事件处理程序、委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52484554/