Last active
August 23, 2017 06:01
-
-
Save parwatcodes/fb435fb3ce5b81dd21d438deea890d61 to your computer and use it in GitHub Desktop.
Why we have to bind this in react, if not bind we have to use arrow function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class HelloWorld extends React.Component { | |
constructor(props) { | |
super(props); | |
this.state = { message: 'Hi' }; | |
} | |
logMessage() { | |
console.log(this.state.message); | |
} | |
render() { | |
return ( | |
// here what does this represent | |
<input type="button" value="Log" onClick={this.logMessage} /> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
everytime an onclick event is occurred logMessage is bound to the input context
so to bound the instance of component either we have to use bind or arrow notation
after the code is complied
<input type="button" value="Log" onClick={this.logMessage} />
the upper line will be compiled and converted to
React.createElement('input', { onChange: this.logMessage, value: "Log" })
// here this represents component contextremember
this
always represents to the closet object,let A =
{ onChange: this.logMessage, value: "Log" }
A is an object,
and is same as
{ onChange: this.logMessage() { console.log(this.state) } , value: "Log" }
// consoles undefined, cause this here represents object and there is no state property
so the
this
used inside thelogMessage
will be the context of{ onChange: this.logMessage, value: "Log" }
object. So, to solve this issue we have to usebind
to take the component context inthis
, or use=>
notation in function