React 事件处理程序、委托
React event handlers, delegation
我看到了其他一些帖子,但没看懂。
如果我有一个大 table,每行都有一个可点击的操作按钮。
<tbody>
<tr>
<td><button onClick={this.handleClick}></button></td>
</tr>
</tbody>
在 jquery 中,我会将事件绑定到 <tbody>
元素,因为我知道它具有更好的性能。在反应中,如果我将点击事件直接绑定到按钮,实际上会创建多少个处理程序?它会像事件委托一样高效吗?
我尝试在 <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 个不同的问题。
- 是否可以使用委托?是的,您可以在
<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 期望我们设置显式事件处理程序而不是使用委托?授权不是更有效率吗?并不真地。一旦你不 create new handler function for each element 它的开销真的很小。但是作为显式绑定处理程序的优势,您不必担心内存泄漏,因为处理程序被委托给 太常见且寿命足够长的父元素 。这是唯一的原因吗?不,处理程序设置也更适合 "Virtual DOM vs real DOM comparison"。
因此您可以使用委派,但最好在真正成为瓶颈之前不要使用。
我看到了其他一些帖子,但没看懂。
如果我有一个大 table,每行都有一个可点击的操作按钮。
<tbody>
<tr>
<td><button onClick={this.handleClick}></button></td>
</tr>
</tbody>
在 jquery 中,我会将事件绑定到 <tbody>
元素,因为我知道它具有更好的性能。在反应中,如果我将点击事件直接绑定到按钮,实际上会创建多少个处理程序?它会像事件委托一样高效吗?
我尝试在 <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 个不同的问题。
- 是否可以使用委托?是的,您可以在
<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 期望我们设置显式事件处理程序而不是使用委托?授权不是更有效率吗?并不真地。一旦你不 create new handler function for each element 它的开销真的很小。但是作为显式绑定处理程序的优势,您不必担心内存泄漏,因为处理程序被委托给 太常见且寿命足够长的父元素 。这是唯一的原因吗?不,处理程序设置也更适合 "Virtual DOM vs real DOM comparison"。
因此您可以使用委派,但最好在真正成为瓶颈之前不要使用。