react中事件绑定的三种方式

  • 在执行事件上bind
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import React, { Component } from 'react';

class Progress extends Component {
handleClick() {
console.log('this: %o', this.handleClick)
}

render() {
return (
<div className="center">
<button onClick={this.handleClick.bind(this)}>按钮</button>
</div>
);
}
}

export default Progress;
  • 在构造器内声明
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import React, { Component } from 'react';

class Progress extends Component {
constructor(props) {
super(props);
this.state = {}

this.handleClick = this.handleClick.bind(this)
}

handleClick() {
console.log('this: %o', this.handleClick)
}

render() {
return (
<div className="center">
<button onClick={this.handleClick}>按钮</button>
</div>
);
}
}

export default Progress;
  • 使用箭头函数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import React, { Component } from 'react';

class Progress extends Component {
handleClick = () => {
console.log('this: %o', this.handleClick)
}

render() {
return (
<div className="center">
<Button onClick={this.handleClick}>按钮</Button>
</div>
);
}
}

export default Progress;