0

I have created a component in React and I'm using some function in it e.g.

class A {
   changeDid(e) {

  }
   render() {
    return (
      <input type="text" onChange{this.changeDid.bind(this)}>
    )
  }
}

I want to understand a line this.changeDid.bind(this) can anyone help me on this ??

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143

2 Answers2

3

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

this.changeDid.bind(this) means that in changeDid this will be refer to A, so you can get methods that related to A.

class A {
  changeDid(e) {
     this.someMethod();
  }

  someMethod() {
    // ... 
  }

  render() {
    return (
      <input type="text" onChange={this.changeDid.bind(this)}>
    )
  }
}

but if you pass to onChange={ this.changeDid }, this will refer to global scope (in browser it is window, or undefined if you use strict mode), and previous example will not work, because someMethod exists in A but not in window

Oleksandr T.
  • 76,493
  • 17
  • 173
  • 144
1

I've created a simple example for you.

class Example extends React.Component {
  constructor(){
    this.state = {
      item : 'hello World'
    }
    /* this.click = this.click.bind(this) */
  }
  click(){
     console.log(this)
     console.log(this.state.item)
  }
    render(){
    return <div>
       <button onClick={this.click}>Click Me</button>
    </div>
  }
}

React.render(<Example />, document.getElementById('container'));

So if you click on a button you will get next in console :

 console.log(this) // undefined 
 console.log(this.state.item) // Type Error, Cannot read property 'state' of undefined

That's occurs because inside click method this links to the undefined, but we want to display our states.

How can you fix it? To make sure that we get correct context inside click method we bind(this) it. remove comments from this line /* this.click = this.click.bind(this) */ and you will get correct behavior of your method.

Worked example fiddle

I hope it will help you.

Thanks.

The Reason
  • 7,705
  • 4
  • 24
  • 42