调用事件
类似于原生的点击事件onclick=“event()”,React中通过onClick={function}的形式来实现事件处理。
例如:
<div onClick={this.handler}>click me</div>
需要注意的是,开发中需要调用的事件处理函数,一般存在于组件中,而要调用是事件处理函数,则需要通过this.函数名来调用该函数。但是由于JavaScript中this绑定的问题,所以在使用this时则需要为该函数绑定this,主要有以下几种绑定的方法:
使用箭头函数定义事件处理函数:
handler = () => {
console.log(this);
}
render() {
return (
<div onClick={this.handler}>click me</div>
)
}
在模板中调用事件处理函数时,使用箭头函数定义一个函数并返回该事件处理函数:
//定义事件处理函数
handler() {
console.log(this);
}
render() {
return (
<div onClick={(e) => this.handler(e)}>click me</div>
)
}
在构造函数中使用bind强制绑定:
constructor(props) {
supper(props);
this.handler = this.handler.bind(this);
}
传递参数
在React中给事件处理函数传递参数只需在指定形参位置,写入需要传递的数据即可。
例如:
handler(name) {
console.log(name);
}
render() {
return (
<div onClick={(e) => this.handler(‘WJCHumble’, e)}>click me</div>
)
}
如果你和我同样是一个young coder!
欢迎关注本人公众号Code center——春繁秋实,年年常茂。
