-
-
Save parwatcodes/fb435fb3ce5b81dd21d438deea890d61 to your computer and use it in GitHub Desktop.
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} /> | |
); | |
} | |
} |
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} />
);
}
}
class HelloWorld extends React.Component {
constructor(props) {
super(props);
this.state = { message: 'Hi' };
}
logMessage() {
// here this represents the <input tag context
console.log(this.state.message);
}
render() {
return (
// logMessage is passing this context of input to logMessage method
<input type="button" value="Log" onClick={this.logMessage} />
);
}
}
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 context
remember 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 the logMessage
will be the context of { onChange: this.logMessage, value: "Log" }
object. So, to solve this issue we have to use bind
to take the component context in this
, or use =>
notation in function
to call
logMessage
in onclick event either i have to bind it, or use arrow notation to definelogMessage
function, but how does the process work