MENU
Binding
A component class method must be bound before it can be used to handle events. There are three ways to bind a function to an event:1. Calling .bind(this) in the constructor, eg.:
RESETRUNFULL
class Toggle extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick() { // …
}
render() {
return (<button onClick={this.handleClick}>…</button>);
}}
2. Using the experimental public class fields syntax, eg.:
RESETRUNFULL
class LoggingButton extends React.Component {
handleClick = () => { // …
}
render() {
return (<button onClick={this.handleClick}>Click me</button>);
}}
3. Using an inline arrow function, eg.:
RESETRUNFULL
class LoggingButton extends React.Component {
handleClick() { // …
}
render() {
return (<button onClick={() => this.handleClick()}>Click me</button>);
}}