react事件点击
绑事件注意的:
React事件的命名采用小驼峰式(camelCalss)法命名
在react中正常写事件的时候,this的值是undefined
undefined解决办法:
1.es6箭头函数
```
alertESsix = ()=>{
//ES6的 箭头函数的this指向上级最近的作用域。
console.log(this)
console.log("我被ES6点击了")
}
```
2.bind改变this指向
```
//首先在react生命周期constructor里面更改this指向再去定义事件
constructor(props){
super(props)
// 为了在回调中使用 `this`,这个绑定是必不可少的
this.alretTip = this.alretTip.bind(this);
}
```
3.正常函数体调用的时候用箭头函数条用(容易传参)
```
<button onClick={() =>{this.alertThree()}}> 点击第三种打印方法</button>
```
事件的冒泡默认
e.preventDefault(); 给a标签 添加事件会跳转
e.storPropagation(); 事件冒泡
总结:
```
alretTip(e){
// 事件命名格式 onClick onChange 驼峰命名法
// 正常函数时 this 为undefind , 1.onClick={this.函数名} 2.bind方法 改变this this.alretTip = this.alretTip.bind(this);
//3.es6箭头函数 4.正常函数体 “ 调用时增加箭头函数 onClick={()=>{this.alertThree()}}
// 阻止默认事件, 与原js return false;
console.log(this)
console.log(this.props)
console.log("我被点击了")
}
```