React 中的组件:函数式 vs. 类组件
发布: (2026年1月5日 GMT+8 02:30)
3 min read
原文: Dev.to
Source: Dev.to
什么是 React 组件?
React 组件是用于 UI 的可复用构建块。它们让你能够把 UI 拆分成更小、独立的部分。
React 中的组件类型
React 有两种组件:
- 函数式组件(现代,推荐)
- 类组件(较旧)
1. 函数式组件(推荐)
函数式组件是返回 JSX 的 JavaScript 函数。
function Greeting() {
return <h1>Hello, React!</h1>;
}
export default Greeting;
为什么使用函数式组件?
- 更简洁、易读
- 不需要
this关键字 - Hooks(
useState、useEffect等)只能在函数式组件中使用
2. 类组件(旧方法)
类组件使用 ES6 类并通过 render() 方法返回 JSX。
import React, { Component } from "react";
class Greeting extends Component {
render() {
return <h1>Hello, React!</h1>;
}
}
export default Greeting;
为什么避免类组件?
- 语法更复杂
this关键字可能让人困惑- 不能直接使用
useState等 Hook
组件中的状态
✅ 函数式组件中的状态(使用 useState)
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increase</button>
</div>
);
}
export default Counter;
❌ 类组件中的状态(使用 this.state)
import React, { Component } from "react";
class Counter extends Component {
constructor() {
super();
this.state = { count: 0 };
}
increaseCount = () => {
this.setState({ count: this.state.count + 1 });
};
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={this.increaseCount}>Increase</button>
</div>
);
}
}
export default Counter;
使用 Hook(useState)的函数式组件更短、更清晰。
组件中的 Props
✅ 在函数式组件中使用 Props
function Welcome(props) {
return <h1>Hello, {props.name}!</h1>;
}
// Usage
// <Welcome name="Alice" />
❌ 在类组件中使用 Props
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}!</h1>;
}
}
// Usage
// <Welcome name="Alice" />
函数式组件 vs. 类组件:对比
| 特性 | 函数式组件 | 类组件 |
|---|---|---|
| 语法简洁度 | 简单且清晰 | 较为复杂 |
| 性能 | 更快 | 略慢 |
this 关键字 | 不需要 | 必须使用 |
| 状态管理 | useState Hook | this.state |
| 生命周期方法 | useEffect Hook | componentDidMount 等 |
| 推荐吗? | 是 | 否(遗留) |
结论
- 使用函数式组件,以获得更好的性能和可读性。
- 函数式组件支持 React Hooks(
useState、useEffect等)。 - 类组件 已被视为过时,除非维护遗留代码,否则应避免使用。