Responsive to delegate a normal event handler for a document, what about a related function?

As you know, React automatically delegates the entire event to a document, as does a large list:

handleTodo(){}
render() { todos.map((todo)=><li onClick={this.handleTodo}>{todo.name}</li>)}

will create a to-do list, but the onClick event will delegate the document, right?

BUT, a question about a related function.

handleTodo(todo){/**update todo */}
render(){todos.map((todo)=><li onClick={this.handleTodo.bind(this,todo)}>{todo.name}</li>)}

for each todo, there is another related function due to different parameters. when will these functions be generated? Does React delegate these functions to a document? what if a huge list, are there thousands of related functions that cause performance issues?

+4
source share
1 answer

when will these functions be generated?

, : render. , , render.

(React , .)

?

, React , . , onClick s.

, , , ?

- " "? , :

, .

, todo, . , todo todo .


, , Function.prototype.bind , :

// Wrap `bind` so we can see when it used
if (function foo() {}.name !== "foo") {
  console.log("Note: Your browser JavaScript engine doesn't support the Function#name property");
}
const bind = Function.prototype.bind;
Function.prototype.bind = function(...args) {
  const name = this.name || "(no name)";
  console.log(`Binding "${name}"`);
  return bind.apply(this, args);
};

class Example extends React.Component {
  constructor(...args) {
    super(...args);
    this.state = {items: [1, 2, 3, 4]};
  }
  handler(n) {
    console.log("Clicked, n = " + n);
  }
  render() {
    console.log("Entering render");
    const result =
      <div>
      {this.state.items.map(n => <div key={n} onClick={this.handler.bind(this, n)}>Click me</div>)}
      </div>
    ;
    console.log("Leaving render");
    return result;
  }
}

ReactDOM.render(
  <Example />,
  document.getElementById("react")
);
<div id="react"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.js"></script>
Hide result
+3

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


All Articles