0

(In React Coding) Whenever I click on the screen I would like to compute something by using OnClick event. For that I got a sample code from internet as follows,

<div className="sample" onClick={this.handleClick.bind(this)}>

The handleClick method and <div> resides in the same method. Could anybody explain why binding is required here and why should not we call handleClick() method directly with out binding?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • 2
    This question has already been asked on SO. https://stackoverflow.com/questions/38624799/why-is-it-necessary-to-use-bind-when-working-with-es6-and-reactjs – Grandas Jun 30 '17 at 05:26
  • 2
    Possible duplicate of [Why is it necessary to use bind when working with ES6 and ReactJS?](https://stackoverflow.com/questions/38624799/why-is-it-necessary-to-use-bind-when-working-with-es6-and-reactjs) – Mayank Shukla Jun 30 '17 at 06:10

2 Answers2

2

"this" keyword refers the context of current component (let say Component A) in react. Basically in java-script it refers the current class or function but for react it refers the current component.

If you are not send this with your handleClick method then whenever handleClick method you called then handleClick never know the things(like variables or functions) of component A.

Kiwi Rupela
  • 2,238
  • 5
  • 24
  • 44
1

In JavaScript there is something called context. It includes whats found in the current scope using the this keyword. So by using bind, you are passing the context where handleClick is called into the function handleClick so that this function can use this.values from the bound context.

More info here.

john
  • 1,561
  • 3
  • 20
  • 44