0

Why is

<button onClick={() => this.handleClick(id)} />

equivalent to calling .bind:

<button onClick={this.handleClick.bind(this, id)} />

ref: https://reactjs.org/docs/faq-functions.html

An arrow function expression has a shorter syntax than a function expression and does not have its own this, arguments, super, or new.target.

ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

If arrow function does not have its own this, the 1st handleClick() would have a different this as compared to the 2nd one, no?

kai jie
  • 173
  • 2
  • 2
  • 8

2 Answers2

1
1. <button onClick={() => this.handleClick(id)} />

2. <button onClick={this.handleClick.bind(this, id)} />

yes, both function equally if the handle click would not have expected any id as argument, then you could have written it like:

<button onClick={this.handleClick} />

And this case this will the component whose render is this. to pass arguments to function, you need to write onClick like this. And first of all, onClick expects a function as the value, not a function call. so to convert handleClick into a function that is bound to correct context(this: Component). you need to write it using bind. bind return you a context bounded function. react the docs at mdn for more understanding. bind mdn

simbathesailor
  • 3,681
  • 2
  • 19
  • 30
0
1. <button onClick={() => this.handleClick(id)} />

here this nothing but scope of component in which it is rendered.

So,if above button is rendering inside component A,then this point to A component object.

Note : here this is not arrow function property.Its just inheriting the parent scope which nothing but button->render->component A object.

i.e. lexical scope without explicit binding.

2. <button onClick={this.handleClick.bind(this, id)} />

only diff you are binding this explicitly with bind which is again Component A

RIYAJ KHAN
  • 15,032
  • 5
  • 31
  • 53