Difference between revisions of "Event Handling in React"
From Logic Wiki
| Line 10: | Line 10: | ||
return ( | return ( | ||
<button onClick={this.switchNameHandler}>Switch Name</button> | <button onClick={this.switchNameHandler}>Switch Name</button> | ||
| + | |||
| + | == bind == | ||
| + | in order to use this | ||
| + | <pre> | ||
| + | constructor() { | ||
| + | super(); | ||
| + | this.handleIncrement = this.handleIncrement.bind(this); | ||
| + | } | ||
| + | |||
| + | handleIncrement() { | ||
| + | console.log("increment clicked", this); | ||
| + | } | ||
| + | </pre> | ||
| + | === binding with arrow function === | ||
| + | <pre> | ||
| + | handleIncrement = () => { | ||
| + | console.log("increment clicked", this); | ||
| + | } | ||
| + | </pre> | ||
| + | |||
| + | == Passing event arguments == | ||
| + | <pre> | ||
| + | handleIncrement = product => { | ||
| + | console.log(product); | ||
| + | this.setState({ count: this.state.count + 1 }); | ||
| + | }; | ||
| + | |||
| + | <button onClick={ () => this.handleIncrement(product)}>Increment</button> | ||
| + | </pre> | ||
=== setState === | === setState === | ||
Revision as of 16:02, 20 November 2018
in the class
switchNameHandler = () => {
console.log('clicked');
}
render(){
return (
<button onClick={this.switchNameHandler}>Switch Name</button>
bind
in order to use this
constructor() {
super();
this.handleIncrement = this.handleIncrement.bind(this);
}
handleIncrement() {
console.log("increment clicked", this);
}
binding with arrow function
handleIncrement = () => {
console.log("increment clicked", this);
}
Passing event arguments
handleIncrement = product => {
console.log(product);
this.setState({ count: this.state.count + 1 });
};
<button onClick={ () => this.handleIncrement(product)}>Increment</button>
setState
switchNameHandler = () => {
this.setState({person:{name:'aaa'});
}