Difference between revisions of "Event Handling in React"
From Logic Wiki
(Created page with "Category:React in the class switchNameHandler = () => { console.log('clicked'); } render(){ return ( <button onClick={this.switchNameHandler}>Swit...") |
|||
| (2 intermediate revisions by the same user not shown) | |||
| Line 1: | Line 1: | ||
[[Category:React]] | [[Category:React]] | ||
| − | + | <div style="float:right;">__TOC__</div> | |
| + | == Handling event == | ||
in the class | in the class | ||
| Line 6: | Line 7: | ||
console.log('clicked'); | console.log('clicked'); | ||
} | } | ||
| − | |||
render(){ | render(){ | ||
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 === | ||
| + | |||
| + | switchNameHandler = () => { | ||
| + | this.setState({person:{name:'aaa'}); | ||
| + | } | ||
| + | [[File:State.JPG]] | ||
Latest revision as of 16:04, 20 November 2018
Handling event
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'});
}