0

I have the following code for reactjs:

 class Counter extends React.Component {
       constructor(props) {
          super(props);
          this.state = { count: 0};
       }

       incrementCount() {
          this.setState( {count: this.state.count + 1});
       }
       render() {
          return (
             <div> Count:{this.state.count}&nbsp;
                <button type="button" style={btnCSS}
                   **onClick={ this.incrementCount.bind(this) }>React</button>**
             </div>
          );
       }
    };

in the statement onClick={ this.incrementCount.bind(this) }>React does the first 'this' refer to the button and the second 'this' refer to the onClick event?

DCR
  • 14,737
  • 12
  • 52
  • 115
  • 1
    both refer to the `Counter` class – Hamms Nov 10 '17 at 23:59
  • 1
    so that makes sense for the first 'this' as we need to get incrementCount but why the need to reference the class Counter again in the second 'this' what else could possible be implied? – DCR Nov 11 '17 at 00:01
  • Are you familiar with how [`function.bind`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind) works? This is a common pattern to ensure that class methods are called with the right context, even when passing them around as first-order objects – Hamms Nov 11 '17 at 00:04
  • 1
    Specifically, it's there to make sure that `this.setState` and `this.state` within the `incrementCount` method still refer to the right instance of `Counter` – Hamms Nov 11 '17 at 00:05
  • thanks, just learning. this is really helpful – DCR Nov 11 '17 at 00:05
  • see https://stackoverflow.com/a/10115970/1810460 for more examples – Hamms Nov 11 '17 at 00:07

0 Answers0