React事件处理方式主要有三种。(虽然网上还有其他方法,可是我懒啊。其实三种就够用了、)
关于this的讲解详见之前的文章:3-3 作用域和闭包-this
1、使用箭头函数
render(){
return(
<button onClick={(event)=>{console.log(this.state.number);}}></button>
)
}
箭头函数中this总指向当前组件的实例对象。如果函数的逻辑复杂,可以把函数给封装成组件的一个方法。
render(){
return(
<button onClick={(event)=>{this.handleClick(event);}}></button>
)
}
handleClick(event){
这里定义函数体
}
2. 使用组件方法
直接将组将的方法赋值给元素的事件属性,同事在累的构造函数中,将这个方法的this绑定到当前对象。
constructor(props){
super(props);
this.state={number:0};
this.handleClick = this.handleClick.bind(this);
}
render(){
return(
<button onClick={this.handleClick;}}></button>
)
}
handleClick(event){
这里定义函数体
}
或者像下面这样写
constructor(props){
super(props);
this.state={number:0};
// this.handleClick = this.handleClick.bind(this);这一行就不要了
}
render(){
return(
<button onClick={this.handleClick.bind(this);}}></button>
)
}
handleClick(event){
这里定义函数体
}
但是这样写法,每次render都会创建一个心函数。不过在需要传入额外参数的时候,这么写就有用处了。
constructor(props){
super(props);
this.state={number:0};
// this.handleClick = this.handleClick.bind(this);这一行就不要了
}
render(){
return(
//这里需要给函数传入额外的参数
<button onClick={this.handleClick.bind(this,item);}}></button>
)
}
handleClick(event){
这里定义函数体
}
3. 属性初始化语法
ES7中会自动为class中定义的方法绑定this,例如:
constructor(props){
super(props);
this.state={number:0};
// this.handleClick = this.handleClick.bind(this);这一行就不要了
}
render(){
return(
//这里需要给函数传入额外的参数
<button onClick={this.handleClick;}}></button>
)
}
//实际上也是使用了箭头函数
handleClick = (event) => {
这里定义函数体
}
不一定支持这个属性哦,还是慎用吧。我觉得第二种方法比较好用,
网友评论