类组件(Classcomponent)和函数式组件 (Functionalcomponent)之间有何不同?
在 React 中,类组件 (Class Component) 和 函数式组件 (Functional Component) 都是用来定义 UI 的两种方式,但它们在语法、生命周期管理、状态处理等方面有显著区别。
定义方式
| 类型 | 定义示例 |
|---|---|
| 类组件 | jsx<br>class MyComponent extends React.Component {<br> render() {<br> return <div>Hello, {this.props.name}</div>;<br> }<br>}<br> |
| 函数组件 | jsx<br>function MyComponent(props) {<br> return <div>Hello, {props.name}</div>;<br>}<br> |
状态管理(State)
| 特性 | 类组件 | 函数组件 |
|---|---|---|
| 状态定义 | this.state = { count: 0 } |
const [count, setCount] = useState(0) |
| 状态更新 | this.setState({ count: this.state.count + 1 }) |
setCount(count + 1) |
| 是否支持 Hooks | ❌ 不支持 | ✅ 支持所有 Hooks(useState、useEffect、useMemo等) |
生命周期(Lifecycle)
| 生命周期 | 类组件写法 | 函数组件对应写法 |
|---|---|---|
| 初始化 | componentDidMount() |
useEffect(() => { ... }, []) |
| 更新 | componentDidUpdate() |
useEffect(() => { ... }) |
| 卸载 | componentWillUnmount() |
useEffect(() => { return () => {...} }, []) |
this 的区别
| 比较点 | 类组件 | 函数组件 |
|---|---|---|
是否使用 this |
✅ 需要(访问 props/state) | ❌ 不需要 |
| 绑定问题 | 必须在构造函数中绑定方法(或用箭头函数) | 自动闭包捕获上下文,无需绑定 |
性能与简洁性
-
函数组件更轻量、可读性高
-
类组件稍显冗长,逻辑分散在多个生命周期函数中
-
React 团队官方推荐:优先使用函数组件 + Hooks
例子对比
类组件版
class Counter extends React.Component {
state = { count: 0 };
componentDidMount() {
console.log('Mounted!');
}
render() {
return (
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Count: {this.state.count}
</button>
);
}
}
函数组件版(推荐)
import { useState, useEffect } from 'react';
function Counter() {
const [count, setCount] = useState(0);
useEffect(() => {
console.log('Mounted!');
}, []);
return (
<button onClick={() => setCount(count + 1)}>
Count: {count}
</button>
);
}
总结表
| 特性 | 类组件 | 函数组件 |
|---|---|---|
| 写法简洁 | ❌ | ✅ |
| 支持 Hooks | ❌ | ✅ |
| 性能优化 | 一般 | 较好(React.memo等) |
| 生命周期写法 | 复杂 | 简洁(useEffect统一处理) |
| 推荐使用 | 不推荐新项目使用 | ✅ 官方推荐 |
一句话总结
“类组件是旧时代的产物,函数组件是现代 React 的主流。”
浙公网安备 33010602011771号