I am a newbie who just started studying React.
I am very confused with bind()
method that is used within onClick
inside the component tag.
Below is the snippet of my code. This code works, but I am not really sure what bind() is doing and how is it working.
When I click the button, I am passing "Jack" as the argument of switchNameHandler
method.
When the switchNameHandler
is executed, what is inside the argument newName
?
And what are this
referring to inside the switchNameHandler
method and bind(this, 'Jack')
line? What exactly is bind(this, 'Jack')
doing?
...
switchNameHandler = (newName) => {
this.setState({
persons: [
{name: newName, age: 21},
]
});
}
render() {
return (
<div className="App">
<button onClick={this.switchNameHandler.bind(this, 'Jack')}>Switch Name</button>
<Person
name={this.state.persons[0].name}
age={this.state.persons[0].age}></Person>
</div>
);
}
...