Below is code snippets that works,
State-
state = {
name : '',
age : ''
}
onChangeHandler-
nameHandler = (event) =>{
this.setState({name: event.target.value});
}
UI-
<input type = "text" onChange = {this.nameHandler} value = {this.state.name}/>
But why does the following not work?
State-
state = {
name : '',
age : ''
}
onChangeHandler-
nameHandler = (event) =>{
this.setState({name: event.target.value});
}
UI-
<input type = "text" onChange = {(event) =>this.nameHandler} value = {this.state.name}/>
Not even the following,
state = {
name : '',
age : ''
}
onChangeHandler-
nameHandler(event){
this.setState({name: event.target.value})
}
UI-
<input type = "text" onChange = {(event) =>this.nameHandler} value = {this.state.name}/>
I understand the reason for my question is lacking knowledge in arrow function theory.
Please share detailed reason
Consider the second example
<input type = "text" onChange = {(event) =>this.nameHandler} value = {this.state.name}/>
Here you are not calling the original function. Here is just a wrapper function which returns another function. Events handlers are not effected by the return value.
<input type = "text" onChange = {(event) =>this.nameHandler(event)} value = {this.state.name}/>
change it following to call the function onChange: this.nameHandler --> this.nameHandler()
<input type = "text" onChange = {(event) =>this.nameHandler(event)} value = {this.state.name}/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With