绑定时使用箭头函数
class App extentds Component { state = { count: 0 } onClick(){ this.setState({ count: this.state.count + 1 }) } render(){ return ( <div> <p>{this.state.count}</p> <button onClick={() => this.onClick()}></button> </div> ) }}
bind
class App extentds Component { constructor(props){ super(props); this.state = { count: 0 } this.onClick = this.onClick.bind(this); // 实例上的 onClick 指向原型上的 onClick 并改变 this 的指向 } onClick(){ this.setState({ count: this.state.count + 1 }) } render(){ return ( <div> <p>{this.state.count}</p> <button onClick={ this.onClick }></button> </div> ) }}
public class fields 语法 ES7
class App extentds Component { state = { count: 0 } // 使用箭头函数在类中定义,会把方法定义至实例上 onClick = () => { this.setState({ count: this.state.count + 1 }) } render(){ return ( <div> <p>{this.state.count}</p> <button onClick={ this.onClick }></button> </div> ) }}