This is for explaining the usage of .bind(this)
in React components.
Firstly I will create a React component with JS ES6 class
.
class Greeting extends React.Component {
constructor(props){
super(props);
this.state = {
text: ""
}
//the binding section
this.clicked = this.clicked.bind(this);
}
clicked(){
this.setState=({
text: "Hello!"
});
render() {
<button onClick={this.clicked}>Click</button>
<h1>{this.state.text}</h1>
}
}
}
ReactDOM.render(<Greeting />, document.querySelector("body"));
As you can see, I assigned this.clicked
to this.clicked.bind(this)
.
At there the this
keyword in the bind method mean the whole component.
And the .bind()
method give access the whole component’s data to the this.clicked
function.
So that when the this.setState
is called in the this.clicked
the this
mean the component, not the this.clicked
function.
Therefore you can change the data of the component state.
For more: