React--函数组件和类组件

发布于:2025-05-23 ⋅ 阅读:(27) ⋅ 点赞:(0)

React 中的函数组件和类组件是两种定义组件的方式,它们有以下主要区别:

1. 语法与定义方式

  • 函数组件: 是 JavaScript 函数,接收 props 作为参数,返回 JSX。

    const MyComponent = (props) => {
      return <div>Hello, {props.name}</div>;
    };
    
  • 类组件: 继承自 React.Component,必须定义 render() 方法返回 JSX。

    class MyComponent extends React.Component {
      render() {
        return <div>Hello, {this.props.name}</div>;
      }
    }
    

2. 状态管理

  • 函数组件: 最初无状态,需使用 Hooks(如 useState)管理状态。

    const Counter = () => {
      const [count, setCount] = useState(0);
      return <button onClick={() => setCount(count + 1)}>{count}</button>;
    };
    
  • 类组件: 通过 this.state 和 this.setState 管理状态。

    class Counter extends React.Component {
      state = { count: 0 };
      increment = () => {
        this.setState({ count: this.state.count + 1 });
      };
      render() {
        return <button onClick={this.increment}>{this.state.count}</button>;
      }
    }
    

3. 生命周期方法

  • 函数组件: 使用 useEffect Hook 替代生命周期方法。

    useEffect(() => {
      // 组件挂载后执行
      return () => {
        // 组件卸载前执行
      };
    }, []); // 依赖项为空数组时,等效于 componentDidMount 和 componentWillUnmount
    
  • 类组件: 有完整的生命周期方法(如 componentDidMount、componentDidUpdate、componentWillUnmount)。

    class MyComponent extends React.Component {
      componentDidMount() {
        // 组件挂载后执行
      }
      componentWillUnmount() {
        // 组件卸载前执行
      }
    }
    

4. 性能优化

  • 函数组件: 通过 React.memo 浅比较 props 避免重复渲染。

    const MyComponent = React.memo((props) => {
      return <div>{props.value}</div>;
    });
    
  • 类组件: 通过 shouldComponentUpdate 或继承 React.PureComponent 实现。

    class MyComponent extends React.PureComponent {
      // 自动浅比较 props 和 state
    }
    

5. 上下文与 refs

  • 函数组件: 使用 useContext 和 useRef Hooks。

    const value = useContext(MyContext);
    const ref = useRef(null);
    
  • 类组件: 通过 static contextType 或 Context.Consumer,以及 React.createRef()。

    static contextType = MyContext;
    ref = React.createRef();
    

6. 适用场景

  • 函数组件: 更简洁,适合无状态组件或逻辑简单的组件,是 React 的推荐写法。
  • 类组件: 适合复杂逻辑(如需要访问生命周期方法或使用 this),但逐渐被函数组件替代。

总结

特性 函数组件 类组件
语法 函数 / 箭头函数 继承 React.Component
状态管理 Hooks(如 useState) this.state 和 setState
生命周期 useEffect Hook 完整生命周期方法
性能优化 React.memo shouldComponentUpdate
适用场景 无状态 / 简单逻辑 复杂逻辑 / 生命周期依赖

现代 React 开发中,函数组件配合 Hooks 已成为主流,因为它们更简洁、可复用性更高,并且能更好地处理状态和副作用。


网站公告

今日签到

点亮在社区的每一天
去签到