在React组件中处理事件最容易出错的地方是事件处理函数中this的指向问题,因为ES6 class并不会为方法自动绑定this到当前对象。React事件处理函数的写法主要有三种方式,不同的写法解决this指向问题的方式也不同。
一、使用箭头函数
直接在React元素中采用箭头函数定义事件的处理函数,例如:
class MyComponent extends React.Component{
constructor(props){
super(props);
this.state = {number:0};
}
render(){
return(
<button onClick={(event)=>{console.log(this.state.number);}} >
)
}
}
因为箭头函数中的this指向的是函数定义时的对象,所以可以保证this总是指向当前组件的实例对象。当事件处理逻辑比较复杂时,如果把所有的逻辑直接写在onClick的大括号内,就会导致 render函数变得臃肿,不容易直观地看出组件的UI结构,代码可读性也不好。这时,可以把逻辑封装成组件的一个方法,然后在箭头函数中调用这个方法。代码如下:
class MyComponent extends React.Component{
constructor(props){
super(props);
this.state = {number:0};
}
//每次点击一次Button,state中的number增加1
handleClick(event){
const number = ++this.state.number;
this.setState({
number:number
});
}
render(){
return(
<div>
<div>{this.state.number}</div>
<button onClick={(event)=> {this.handleClick(event);}} >
</div>
)
}
}
直接在render方法中为元素事件定义事件处理函数,最大的问题是,每次render调用时,都会重新创建一次新的事件处理函数,带来额外的性能开销,组件所处层级越低,这种开销就越大,因为任何一个上层组件的变化都可能会触发这个组件的render方法。当然,在大多数情况下,这种性能损失是可以不必在意的。
二、使用组件方法
直接将组件的方法赋值给元素事件属性,同时在类的构造函数中,将这个方法的this绑定到当前对象。例如:
class MyComponent extends React.Component{
constructor(props){
super(props);
this.state = {number:0};
this.handleClick = this.handleClick.bind(this);
}
//每次点击一次Button,state中的number增加1
handleClick(event){
const number = ++this.state.number;
this.setState({
number:number
});
}
render(){
return(
<div>
<div>{this.state.number}</div>
<button onClick={this.handleClick} >
</div>
)
}
}
这种方式的好处是每次render不会重新创建一个回调函数,没有额外的性能损失。但在构造函数中,为事件处理函数绑定this,尤其是存在多个事件处理函数需要绑定时,这种模版式的代码还是会显得繁琐。
有些开发者还习惯在为元素的事件属性赋值时,同时为事件处理函数绑定this,例如:
class MyComponent extends React.Component{
constructor(props){
super(props);
this.state = {number:0};
}
//每次点击一次Button,state中的number增加1
handleClick(event){
const number = ++this.state.number;
this.setState({
number:number
});
}
render(){
return(
<div>
<div>{this.state.number}</div>
<button onClick={this.handleClick.bind(this)} >
</div>
)
}
}
使用bind会创建一个新的函数,因此这种写法依然存在每次render都会创建一个新的函数的问题。但在需要为处理函数传递额外参数时,这种写法就有了用武之地。例如,下面的例子需要为handleClick传入参数item
class MyComponent extends React.Component{
constructor(props){
super(props);
this.state = {
list:[1,2,3,4],
current:1
};
}
//点击每一项时,将点击项设置为当前选中项,因此需要把点击项作为参数传递
handleClick(item,event){
this.setState({
current:item
});
}
render(){
return(
<ul>
{this.state.list.map((item)=>({
/*bind除了绑定this,还绑定item作为参数,供handleClick使用 */
<li className={this.state.current ===item?'current':''} onClick={this.handleClick.bind(this,item)}>
</li>
}))}
</ul>
)
}
}
三、属性初始化语法(property initializer syntax)
使用ES 7 的property initializers会自动为class中定义的方法绑定this。
class MyComponent extends React.Component{
constructor(props){
super(props);
this.state = {number:0};
}
//ES7 的属性初始化语法,实际上也是使用了箭头函数
handleClick = (event)=>{
const number = ++this.state.number;
this.setState({
number:number
});
}
render(){
return(
<div>
<div>{this.state.number}</div>
<button onClick={this.handleClick} >
</div>
)
}
}
这种方式既不需要在构造函数中手动绑定this,也不需要担心组件重复渲染导致的函数重复创建问题。
- 摘自《React进阶之路》