React的事件处理和DOM元素的很相似,但是还是有些不同:

绑定事件方式

传统: onclick 属性小写

reatc: onClick on+事件名 驼峰原则

阻止事件默认

传统: <a href="#" onclick="javascript:return false;">链接</a>

react:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class PreventDefault extends Component{
constructor(props){
super(props)
this.handleClick = this.handleClick.bind(this)
}

handleClick = () => { // handleClick(){}可以写成这种形式
e.preventDefault();
console.log('preventDefault');
}

render(){
return(
<div>
<a href="#" onClick={this.handleClick}>阻止默认行为</a>
</div>
)
}
}

回调函数的this绑定

传统: 自动绑定this

react: 直接输出this为undefined,三种方式绑定:

一、onClick={this.handleClick}情况下在类的构造函数手动绑定:

1
2
3
4
constructor(props){
super(props)
this.handleClick = this.handleClick.bind(this)
}

二、onClick={this.handleClick}情况下使用属性初始化器绑定

1
2
3
handleClick = () => {
console.log('this is', this);
}

三、箭头函数
此时函数的声明方式可以写成上面案例中注释的方式

1
onClick={(e)=>{this.handleClick(e)}}

向事件处理函数传递参数

一、通过Function.prototype.bind方式传递

1
<button onClick={this.handleClick.bind(this,id)}>点击按钮</button>

二、通过箭头函数传递

1
<button onClick={(e)=>this.handleClick(id,e)}>点击按钮</button>

上面两个例子中,参数 e 作为 React 事件对象将会被作为第二个参数进行传递。通过箭头函数的方式,事件对象必须显式的进行传递,但是通过 bind 的方式,事件对象以及更多的参数将会被隐式的进行传递。
值得注意的是,通过 bind 方式向监听函数传参,在类组件中定义的监听函数,事件对象 e 要排在所传递参数的后面,例如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Propper extends React.Component{
constructor(){
super()
this.state = { name: 'hello react' }
}

handleClick (name, e){

}

render(){
return(
<div>
<p>hello</p>
<a href="www.baidu.com" onClick={this.handleClick.bind(this, this.state.name)}>链接</a>
</div>
)
}
}