React中事件this的绑定方式

在React中创建事件,绑定this时长发生,那this是如何进行绑定的呢?

1、一般情况下我们会把this绑定在构造函数中

1
2
3
4
5
6
7
8
9
10
11
12
13
controuctor() {
super();

let handleDefault = this.handleDefault.bind(this);
}

render() {
return (
<div>
<a href="#" onClick={this.handleDefault}></a>
</div>
);
}

这样做的好处在于,我们可以清晰的看到当前组件中的事件到底有哪些,对于性能优化也存在一定的好处

2、另一种情况我们会在事件上 绑定this,例如下面的代码:

1
2
3
4
5
6
7
8
9
...
render() {
return (
<div>
<a href="#" onClick={{this.handleClick().bind(this)}}></a>
</div>
);
}
...

3、再者就是利用箭头函数进行绑定

1
2
3
4
5
6
7
8
9
10
11
...
handleCilick = () => {
// coding ...
}

...
render() {
renturn(
<a href="#" onClick={(e) => this.handleClink(e)}></a>
);
}

事件传参

1
2
3
4
5
6
7
8
9
10
handleClick (e, id) => {
// coding ...
}

render() {
return(
<a href="#" onClick={(e) => this.handleClick(id, e)}>Cliclk Me</a>
<a href="#" onClick={this.handleClick.bind(this, id)}>Cliclk Me</a>
);
}

上面这两者是等价的;
拿官方上面的一句话说明:
值得注意的是,通过 bind 方式向监听函数传参,在类组件中定义的监听函数,事件对象 e 要排在所传递参数的后面

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Popper extends React.Component{
constructor(){
super();
this.state = {name:'Hello world!'};
}

preventPop(name, e){ //事件对象e要放在最后
e.preventDefault();
alert(name);
}

render(){
return (
<div>
<p>hello</p>
{/* Pass params via bind() method. */}
<a href="https://reactjs.org" onClick={this.preventPop.bind(this,this.state.name)}>Click</a>
</div>
);
}
}

0%