react 事件绑定

1.第一种,官方推介,在construcotr中定义事件

constructor(props) { super(props); this.state = {isToggleOn: true}; // 这边绑定是必要的,这样 `this` 才能在回调函数中使用 this.handleClick = this.handleClick.bind(this); }

<button onClick={this.handleClick}> {this.state.isToggleOn ? 'ON' : 'OFF'} </button>

2.通过es6语法箭头函数来使用

handleClick = () => { console.log('this is:', this); }

render() { return ( <button onClick={this.handleClick}> Click me </button> ); }

3.handleClick() { console.log('this is:', this); }

render() { // 这个语法确保了 `this` 绑定在 handleClick 中 return ( <button onClick={(e) => this.handleClick(e)}> Click me </button> ); }

4..handleClick() { console.log('this is:'this)}

render() { // 这个语法确保了 `this` 绑定在 handleClick 中 return ( <button onClick={this.handleClick.bind(this)}Click me </button)}

posted @ 2019-07-25 11:33  愤怒小鸟  阅读(339)  评论(0)    收藏  举报