类组件(Class component)和 函数式组件(Functional component) 之间有何区别?

类组件(Class component)和函数式组件(Functional component)是 React 中两种不同的组件实现方式。

类组件是以 class 形式定义的组件。它继承自 React.Component,并且必须包含 render() 方法来返回组件需要渲染的内容。类组件具有自己的状态(state)和生命周期方法,可以在组件的生命周期内执行特定的操作。

示例:

class ClassComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    };
  }

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

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

函数式组件是以函数形式定义的组件。它是纯函数,没有自己的状态,只接收 props 作为参数,并返回需要渲染的内容。函数式组件通常比类组件更简洁和易于理解,适合只需要根据输入 props 渲染内容的场景。

示例:

function FunctionalComponent(props) {
  const [count, setCount] = useState(0);

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

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={handleClick}>Increment</button>
    </div>
  );
}

区别:

  1. 语法和实现方式不同:类组件使用 class 关键字定义,函数式组件使用函数定义。
  2. 状态管理方式不同:类组件使用 this.setState() 来管理状态,函数式组件使用 useState() 钩子函数来管理状态。
  3. 生命周期不同:类组件具有 componentDidMount、componentDidUpdate、componentWillUnmount 等生命周期方法,函数式组件没有生命周期方法,但可以使用 useEffect 钩子函数来实现类似的功能。
  4. 性能差异:由于类组件有额外的实例化和维护状态的开销,函数式组件通常比类组件性能更好,尤其是在需要频繁更新的情况下。
  5. 代码复用和组合方式不同:由于函数式组件是纯函数,它更容易通过组合和高阶组件等方式进行代码复用。

需要注意的是,React Hooks 的引入让函数式组件也可以拥有状态和生命周期方法,使得开发者可以更灵活地选择使用类组件还是函数式组件。

猜你喜欢

转载自blog.csdn.net/m0_74265396/article/details/135435553