一,react
事件声明
1.react
事件采用驼峰式命名
2.react
事件接收一个函数声明,不是函数调用的形式
//原生
<div onclick="handleClick()"></div>
//react
<div onClick={this.handleClick}></div>
二,class
组件的事件绑定this
问题
1.class
的方法默认不会绑定 this
,如果没有绑定 this.handleClick
的this
并把它传入了 onClick
,当你调用这个函数的时候 this
的值为 undefined
。
class A extends React.Component{
constructor(props){
super(props)
}
handleClick(){
//class的方法默认不会绑定 `this`,this的指向根据调用的方式判断
//没有绑定调用的话this为undefined
this.setState({a:1})
}
render(){
return (
<div onClick={this.handleClick}></div>
)
}
}
2.this
问题的解决方式有三种
(1)在constructor
里使用bind
为方法绑定this
class A extends React.Component{
constructor(props){
super(props)
this.handleClick= this.handleClick.bind(this);
}
handleClick(){
this.setState({a:1})
}
}
(2)在元素上绑定事件时使用箭头函数
class A extends React.Component{
constructor(props){
super(props)
}
handleClick(){
//class的方法默认不会绑定 `this`,this的指向根据调用的方式判断
//没有绑定调用的话this为undefined
this.setState({a:1})
}
render(){
//render里的this指向自身
return (
<div onClick={()=> this.handleClick() }></div>
)
}
}
(3)使用箭头函数声明方法
class A extends React.Component{
constructor(props){
super(props)
}
handleClick=()=>{
//箭头函数的this由父作用域的this判断
this.setState({a:1})
}
render(){
//render里的this指向自身
return (
<div onClick={this.handleClick}></div>
)
}
}
三,react
事件传递参数
1.要在绑定事件的位置给事件传参有两种方式,
(1)通过bind
,使用bind
会隐式传入事件对象e
,作为函数的最后一个参数。
<button onClick={this.deleteRow.bind(this, id)}>Delete Row</button>
(2)通过箭头函数,使用箭头函数需要主动传入事件对象e
。
<button onClick={(e) => this.deleteRow(id, e)}>Delete Row</button>
<button onClick={this.deleteRow.bind(this, id)}>Delete Row</button>