一、类组件的问题
自从React推出Hooks之后,函数组件写法大行其道,而类组件写法日渐式微。为什么会这样呢? 我觉得有以下三个原因:
原因一、因为this带来的问题:
有一个著名的案例展示了类组件this带来的问题,下面我将其本土化复现一下这个案例。
import React from "react"
const ProfileFunction: React.FC<{goods:string}> = (props) => {
const showMessage = () => {
alert(`你下单的是“${props.goods}”!` )
}
const handleClick = () => {
setTimeout(showMessage, 3 * 1000)
}
return (
<button onClick={handleClick}>购买</button>
)
}
class ProfileClass extends React.Component< { goods: string }, // props 类型
{} // state 类型
> {
showMessage = () => {
alert(`你下单的是“${this.props.goods}”!` )
}
handleClick = () => {
setTimeout(this.showMessage, 3 * 1000)
}
render() {
return <button onClick={this.handleClick}>购买</button>
}
}
export default class App extends React.Component {
state = {
goods: '苹果',
};
render() {
return (
<>
<label>
请选择:
<select
value={this.state.goods}
onChange