React 元素的事件处理和 DOM 元素的很相似,但是有一点语法上的不同:
- React 事件的命名采用小驼峰式(camelCase),而不是纯小写。
- 使用 JSX 语法时你需要传入一个函数作为事件处理函数,而不是一个字符串。
原生DOM的写法:
<button onclick="handler">点击</button>
React的写法:
<button onClick={this.handler}>点击</button>
在 React 中另一个不同点是你不能通过返回 false
的方式阻止默认行为。你必须显式的使用 preventDefault。
import React from "react";
class Event extends React.Component{
handler(e){
e.preventDefault();
console.log("点击了");
}
render() {
const element=<div>
<button onClick={this.handler}>点击</button>
</div>
return element
}
}
export default Event;
在React中的事件处理中,最重要的就是所绑定事件的this问题:
import React from "react";
class Event extends React.Component{
handler(){
console.log("this is" ,this); //点击之后 this is undefined
}
render() {
const element=<div>
<button onClick={this.handler}>点击</button>
</div>
return element
}
}
export default Event;
在 JavaScript 中,class 的方法默认不会绑定this,因此在handler方法中的this就是undefined。
如何解决这种情况:
1.在调用方法的时候直接使用bind改变其this的指向;
class Event extends React.Component{
handler(){
console.log("this is" ,this);
}
render() {
const element=<div>
<button onClick={this.handler.bind(this)}>点击</button>
</div>
return element
}
}
2.在构造函数中对方法的this进行绑定;
class Event extends React.Component{
constructor(props) {
super(props);
this.handler=this.handler.bind(this);
}
handler(){
console.log("this is" ,this);
}
render() {
const element=<div>
<button onClick={this.handler}>点击</button>
</div>
return element
}
}
3.将方法写成箭头函数
class Event extends React.Component{
handler=()=>{
console.log("this is" ,this);
}
render() {
const element=<div>
<button onClick={this.handler}>点击</button>
</div>
return element
}
}
4.在调用的时候使用箭头函数
class Event extends React.Component{
handler(){
console.log("this is" ,this);
}
render() {
const element=<div>
<button onClick={event=>this.handler(event)}>点击</button>
</div>
return element
}
}
四种方法的本质就是改变this的指向,前两种方法通过bind的形式改变this的指向,让其指向class类组件中的this。箭头函数的this指向箭头函数定义时所处的对象,而不是箭头函数使用时所在的对象,也就是说箭头函数在定义的时候就已经给它绑定的this,本质也是改变this的指向。