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(useStateuseEffect 等)只能在函数式组件中使用

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 Hookthis.state
生命周期方法useEffect HookcomponentDidMount
推荐吗?否(遗留)

结论

  • 使用函数式组件,以获得更好的性能和可读性。
  • 函数式组件支持 React HooksuseStateuseEffect 等)。
  • 类组件 已被视为过时,除非维护遗留代码,否则应避免使用。
Back to Blog

相关文章

阅读更多 »

SQL 让我感到不舒服。

在我实际的、非理论的理解中,object‑oriented programming 并不仅仅是传统 functional paradigm 的一种替代方案,而常常感觉像是……

Web生态系统内战

markdown !Javadhttps://media2.dev.to/dynamic/image/width=50,height=50,fit=cover,gravity=auto,format=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads...