在使用react类组件中绑定事件有以下四种方式(若有需要,推荐使用第一种方式):
import React, { Component } from "react";
class Cat extends Component {
constructor() {
super();
// 第四种对应处理
this.catSayd = this.catSayd.bind(this);
}
// 第一种
catSaya = () => {
alert("hello cat a");
};
// 第二种
catSayb() {
alert("hello cat b");
}
// 第三种
catSayc() {
alert("hello cat c");
}
// 第四种
catSayd() {
alert("hello cat d");
}
render() {
return (
<>
<button onClick={this.catSaya}>Cat say a</button>
<button onClick={this.catSayb.bind(this)}>Cat say b</button>
<button onClick={() => this.catSayc()}>Cat say c</button>
<button onClick={this.catSayd}>Cat say d</button>
</>
);
}
}
export default Cat;
从上面四种事件绑定方式可以看出,类组件与函数组件很大的不同之处在于有个this,所以在类组件中你要时时刻刻注意this指向的问题而在函数组件中就不需要考虑。
而且类组件与函数组件还有一个区别就是:类组件有可以有状态(sate)所以也被称为状态组件而函数组件没有。但在react 16.8 hooks出来之后,官方力推使用react hooks实现状态组件,摒弃类组件的使用。利用react hooks中用useState管理状态,useEffect替换类组件中生命周期钩子函数,从而替代类组件的使用随之也解决了其中this指向问题的这一痛点,在hooks的加持下也使得react代码变得更加简单易懂。
import React, { useState, useEffect } from "react";
function Cat() {
const [count, setCount] = useState(0);
function catSay() {
alert(`hello cat count=${count}`);
}
useEffect(() => {
console.log(count);
},[count]);
return (
<>
<button onClick={()=>{setCount(count+1)}}>count++ = {count}</button>
<button onClick={catSay}>cat catSay</button>
</>
);
}
export default Cat;