事件
事件必知
写法
在jsx
中,事件使用小驼峰法,即onclick
要写成onClick
。
事件绑定
在react16
版下时,事件会自动绑定到当前组件上,但是在react16
以上,我们需要手动将事件绑定到当前组价上。
class TestComponnet extends React.Component{
constructor(){
this.handleClick = this.handleClick.bind(this);
}
}
传参
默认的参数event
<button onClick={this.handleClick}>Click me</button>
handleClick(e){
console.log(e.target)
}
在event的基础上再加其他参数,e为默认参数,无需接收this
<button onClick={this.handleClick.bind(this,param1,param2)}>Click me</button>
handleClick(param1,param2,e){
console.log(param1,param2,e);
}
其他:e.target
对象
e.target.value
e.target.width
e.target.height
event.target
阻止默认事件运行
e.preventDefault();
合成事件
监听键盘事件
{
enter:,
tab:,
delete:,
esc:,
space:,
up:,
down:,
left:,
right:
ctrl:,
alt:,
shift:,
meta:,
}
监听鼠标点击事件
监听鼠标滑动事件
原生事件
使用事件监听器的时候,要在componentDidMount
中增加,在componentWillUnmount
中移除。
// 监听按钮的点击事件
<button ref="myBtn">点击我</button>
componentDidMount:function(){
this.refs.myBtn.addEventListener("click",function(e){
console.log('触发事件')
})
},
componentWillUnmount() {
this.refs.myBtn.removeEventListener('click', function(e){
console.log('移除事件')
});
}
// 监听敲击键盘事件
componentDidMount:function(){
window.addEventListener("keypress",function(e){
code = e.which;
console.log(code);
})
},
componentWillUnmount() {
window.removeEventListener('keypress', function(e){
console.log('移除事件')
});
}
监听全屏事件
注意
map函数中使用事件
我们在jsx
经常使用map去渲染列表,但是要注意,在map函数中使用this.functionName
,this.state
和this.props
等组件下的属性时并不能生效。原因是,此时map中的this指向并不指向当前组件,而是指向window对象,此时直接使用如下代码将找不到this指向的属性或者方法。
{
this.data.map(function(item,index){
return <div onClick={this.handleClick}>{this.state.title}</div>
})
}
解决方法有2种,一种是使用箭头函数,箭头函数中的this将指向当前组件
{
this.data.map((item,index)=>{
return <div onClick={this.handleClick}>{this.state.title}</div>
})
}
另一种则是重新赋值this,手动将this指向当前组件
render:funciton(){
const _this = this;
return (
{
this.data.map(funciton(item,index){
return <div onClick={_this.handleClick}>{_this.state.title}</div>
})
}
)
}
ps:箭头函数是es6语法,请在支持es6的环境中使用