React 入门学习笔记整理(四)—— 事件

1、事件定义

React事件绑定属性的命名采用驼峰式写法,而不是小写。

如果采用 JSX 的语法你需要传入一个函数作为事件处理函数,而不是一个字符串(DOM元素的写法)

在类组件中定义函数,通过this.函数名去调用

class GreateH extends React.Component{
static defaultProps = {name:'CoCo'};
handler(){
console.log("click");
}
render(){
return <div>
<h2 onClick={this.handler}>hello,{this.props.name}</h2>
</div>
}
}

2、this指向

按照第一步中的写法,在handler函数中打印出当前的this:

React 入门学习笔记整理(四)—— 事件

此时this不指向实例,类的方法默认是不会绑定 this 的。如果你忘记绑定 this.handler 并把它传入 onClick, 当你调用这个函数的时候 this 的值会是 undefined。

1)使用bind函数改变this指向

class GreateH extends React.Component{
static defaultProps = {name:'CoCo'};
//在类里直接写成箭头函数
handler(){
console.log("click");
console.log(this);
};
render(){
return <div>
<h2 onClick={this.handler.bind(this)}>hello,{this.props.name}</h2>
</div>
}
}

但是这种render渲染时每次会重新绑定,所以可以写成以下这种:

class GreateH extends React.Component{
constructor(props){
super(props);
//初始化时改变this的指向,给实例添加一个方法,this.handler.bind(this)会返回一个新的函数
this.handler = this.handler.bind(this);
}
static defaultProps = {name:'CoCo'};
handler(){
console.log("click");
console.log(this);
};
render(){
return <div>
<h2 onClick={this.handler}>hello,{this.props.name}</h2>
</div>
}
}

2)写在类中的函数直接写成箭头函数

class GreateH extends React.Component{
static defaultProps = {name:'CoCo'};
//在类里直接写成箭头函数
handler = () => {
console.log("click");
console.log(this);
};
render(){
return <div>
<h2 onClick={this.handler}>hello,{this.props.name}</h2>
</div>
}
}

this在控制台打印出来:

React 入门学习笔记整理(四)—— 事件

3)这里还有一种写法,回调函数中使用 箭头函数:

class GreateH extends React.Component{
static defaultProps = {name:'CoCo'};
//在类里直接写成箭头函数
handler (){
console.log("click");
console.log(this);
};
render(){
return <div>
<h2 onClick={(e)=>this.handler(e)}>hello,{this.props.name}</h2>
</div>
}
}

并不推荐第三种写法,因为每次在GreateH 组件渲染的时候,都会创建一个不同的回调函数,。在大多数情况下,这没有问题。然而如果这个回调函数作为一个属性值传入低阶组件,这些组件可能会进行额外的重新渲染,为了避免性能问题,推荐使用上面两种方式。

3、事件传参

React 入门学习笔记整理(四)—— 事件

上一篇:03-Python入门学习-Python基础


下一篇:React 入门学习笔记整理(五)—— state