【React中函数组件和类组件区别】

时间:2025-05-14 19:30:29

在 React 中,函数组件和类组件是两种构建组件的方式,它们在多个方面存在区别,以下详细介绍:

1. 语法和定义

  • 类组件:使用 ES6 的类(class)语法定义,继承自 React.Component。需要通过 this.props 来访问传递给组件的属性(props),并且通常要实现 render 方法返回 JSX。示例代码如下:
import React, { Component } from 'react';

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

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

  render() {
    return (
      <div>
        <p>计数值: {this.state.count}</p>
        <button onClick={this.increment}>增加</button>
      </div>
    );
  }
}

export default Counter;
  • 函数组件:使用 JavaScript 函数定义,接收 props 作为参数并返回 JSX。在 Rea