简体   繁体   中英

React event handlers, delegation

I saw some other posts on that but didn't understand.

If I have a large table, with a clickable action button in each row.

<tbody>
<tr>
   <td><button onClick={this.handleClick}></button></td>
</tr>
</tbody>

In jquery I would bind the event to the <tbody> element, as I know it have a better performance. In react, if I bind the click event directly to the button, how many handlers are actually created? Is it will be as efficient as event delegation?

I've tried using onClick on the <tbody> and when I access the event object in the console I see this warning:

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().

There are 3 different questions I believe.

  1. Is there possibility to use delegation? Yes, you can set single event handler on <tbody> and check for event.currentTarget.<some attribute to know what it is> .
  2. Why warning is shown? It's because event object is actually reused so if your handler works with Event in async way like

     handleClick(event) { setTimeout(() => { alert(event.target.id); }, 100); } 

    you cannot be sure it's the same event. You should store information you need immediately and later use it

     handleClick(event) { let id_to_store = event.target.id; setTimeout(() => { alert(id_to_store); }, 100); } 
  3. why React expect us to setup explicit event handlers instead of using delegation? Is not delegation much more efficient? Not really. Once you don't create new handler function for each element it has really tiny overhead. But as advantage of explicit binding handler you will not worry about memory leaking because handler is delegated to too common parent element that lives long enough . Is it the only reason? Nope, also handlers set explicitly fits "Virtual DOM vs real DOM comparison" better.

So you can use delegation but better not until it's real bottleneck.

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