Should I use custom event delegation in React JS

React uses event delegation as stated in the documentation here :

Event delegation: React does not actually attach event handlers to the nodes themselves. When React launches, it starts listening for all events at the top level with a single event listener. When a component is mounted or unmounted, event handlers are simply added or removed from the internal mapping.

I have a very common scenario when I have a list of elements and I want an event handler for each element, should I use my custom event delegation and access the target element from the event object to execute logic, or should I attach a separate event listener callbacks for each item in the list and rely on React to take care of performance.

+4
source share
2 answers

Attach an event handler to each. You can view the swap list, most displays will not display 500-1000 items at a time.

class SnipListItemRender extends React.Component {
  render() {
    let SnipSpanSty = {width: 'calc(70% - 142px)'};
    SnipSpanSty.color = (this.props.index === this.props.selectedKey) ? '#b58900' : '#afac87';
    return (
      <div id='SnipDivSty' onclick={this.snipClickHandler} className="FlexBox" style={SnipDivSty}>
        <div id='SelectSnipDivSty' style={SelectSnipDivSty}>
          <JButton btn={selectSnipBtn} parentClickHandler={this.snipClickHandler} />
        </div>
        <span id='SnipSpanSty' style={SnipSpanSty}>{this.props.snippet.snip}</span>
        <JButton btn={SnipBtn} parentClickHandler={this.snipClickHandler} />
      </div>
    );
  }
}

class SnipListItem extends SnipListItemRender {
  snipClickHandler = (buttonid) => { Actions.selectSnipItem(this.props.snippet, buttonid); }
}

let _snipDataMap = function(snip, index) {
  return (
    <li id='SnipsDivLiSty' key={index} style={SnipsDivLiSty}>
      <SnipListItem snippet={snip} index={index} selectedKey={this.props.selectedKey} />
    </li>
  );
}

export default class SnipsView extends React.Component {
  render() {
    let list = this.props.data.map(_snipDataMap, this)
    return (
      <div id='SnipsDivSty' style={SnipsDivSty}>
        <ul id='SnipsDivUlSty' style={SnipsDivUlSty}>
          {list}
        </ul>
      </div>
    );
  }
}
Run codeHide result
+3
source

custom event delegation , . .

    • .
    • . .

this

0

Source: https://habr.com/ru/post/1616091/


All Articles