0

I'm trying here to understand the necessity of the binding I commented ..

class Toggle extends Component {

    constructor(props){
    super(props);

    //this.handleClick = this.handleClick.bind(this);
}


handleClick() {

    console.log(this); 

}


render() {
    return (
        <button onClick={this.handleClick}>
            ...
        </button>
    );
}

}

when I log this inside the handleClick it outputs null ..

I understand that the binding is needed to connect the handleClick method to the Toggle Object ..

But shouldn't the log now look for where was the handleClick invoked or called so it would output global object ?

Or should it have looked for 'what' invoked the handleClick inside the onClick which is the other this that refer there to the Toggle Object so it would output it ?

You Ma
  • 169
  • 1
  • 10
  • 1
    `this` will only refer to the global object if the function is *not* **strict**. Classes are always strict. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode – Felix Kling Jun 10 '17 at 04:41

1 Answers1

1

If you bind handleClick in Toggle, it will indeed bind the method to the class as shown below, when I tried to log the value property in the state. It will throw an error otherwise and you can check it in your browser console (NOT in the code snippet one).

I'm not 100% sure why console.log(this) in unbinded handleClick (The OP of this post had similar problem) returns undefined, but my guess that it could be that it is referring to a null component, as it has undefined for its this value.

class Toggle extends React.Component {
  constructor(props){
    super(props);
    this.state = { value: 'hi' }
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    console.log(this.state.value); 
  }

  render() {
    return (
      <div>
        <button onClick={this.handleClick}>
          Hello
        </button>
        <NullComponent />
      </div>
    );
  }
}

let NullComponent = () => { 
  console.log('calling from null component ', this);
  return null; 
}

ReactDOM.render(<Toggle />, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
Mμ.
  • 7,026
  • 3
  • 22
  • 32