返回

「React」函数组件香在哪儿?与 Class 组件的对比分析

前端

函数组件与 Class 组件的区别

创建方式

函数组件的创建方式更加简洁,只需要使用一个函数即可。而 Class 组件的创建方式则相对复杂,需要使用 class 和 extends 关键字,同时还要定义 constructor 函数、render 函数等方法。

// 函数组件
const MyComponent = () => {
  return <h1>Hello World!</h1>;
};

// Class 组件
class MyComponent extends React.Component {
  render() {
    return <h1>Hello World!</h1>;
  }
}

实现 +1 功能

在函数组件中,实现 +1 功能只需要使用 useState 钩子即可。而在 Class 组件中,实现 +1 功能则需要使用 state 和 setState 方法。

// 函数组件
import { useState } from "react";

const MyComponent = () => {
  const [count, setCount] = useState(0);

  const handleClick = () => {
    setCount(count + 1);
  };

  return (
    <div>
      <h1>Count: {count}</h1>
      <button onClick={handleClick}>+1</button>
    </div>
  );
};

// Class 组件
class MyComponent extends React.Component {
  state = {
    count: 0,
  };

  handleClick = () => {
    this.setState({ count: this.state.count + 1 });
  };

  render() {
    return (
      <div>
        <h1>Count: {this.state.count}</h1>
        <button onClick={this.handleClick}>+1</button>
      </div>
    );
  }
}

模拟 componentDidMount 和 componentDidUpdate

在函数组件中,可以使用 useEffect 钩子来模拟 componentDidMount 和 componentDidUpdate。而在 Class 组件中,可以使用 componentDidMount 和 componentDidUpdate 生命周期钩子。

// 函数组件
import { useEffect } from "react";

const MyComponent = () => {
  useEffect(() => {
    // componentDidMount
  }, []);

  useEffect(() => {
    // componentDidUpdate
  }, [count]);

  return (
    <div>
      <h1>Count: {count}</h1>
      <button onClick={handleClick}>+1</button>
    </div>
  );
};

// Class 组件
class MyComponent extends React.Component {
  componentDidMount() {
    // componentDidMount
  }

  componentDidUpdate(prevProps, prevState) {
    // componentDidUpdate
  }

  render() {
    return (
      <div>
        <h1>Count: {this.state.count}</h1>
        <button onClick={this.handleClick}>+1</button>
      </div>
    );
  }
}

函数组件的优势

函数组件相对于 Class 组件具有以下优势:

  • 创建方式更简洁
  • 性能更好
  • 代码更易于维护
  • 更易于测试

函数组件的使用场景

函数组件适用于以下场景:

  • 简单的 UI 组件
  • 不需要状态的组件
  • 不需要生命周期钩子的组件

结论

函数组件是一种更现代、更简洁、更易于维护的组件类型。在大多数情况下,函数组件都是一个更好的选择。但是,在某些情况下,例如需要使用状态或生命周期钩子时,仍然需要使用 Class 组件。