当前位置: 首页 > news >正文

React--函数组件和类组件

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.memoshouldComponentUpdate
适用场景无状态 / 简单逻辑复杂逻辑 / 生命周期依赖

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

相关文章:

  • 打卡31天
  • Docker的网络介绍
  • linux 查看java的安装路径
  • java并发-线程池
  • gcc还会有自己的头文件呢?
  • 【信息系统项目管理师】第13章:项目资源管理 - 38个经典题目及详解
  • 使用allure生成自动化测试报告
  • systick滴答定时器us延时和毫秒延时
  • 大模型训练全攻略:从参数设置到模型优化
  • FreeCAD傻瓜教程-外螺纹的绘制,利用两个实体进行布尔运算来实现
  • 滚珠丝杆的承载力是多少?
  • HarmonyOS基础组件:Button三种类型的使用
  • Pandoc3.7新特性:存在合并单元格的 HTML 表格会被保留为嵌入的 HTML 表格
  • Ulisses Braga-Neto《模式识别和机器学习基础》
  • 微信小游戏流量主广告自动化浏览功能案例5
  • 【VxWorks 实时操作系统(RTOS)】常用函数汇总
  • Dockerfile指令详解
  • ping、tcpping、psping、paping、hping的区别
  • 从 CANopen到 PROFINET:网关助力物流中心实现复杂的自动化升级
  • 微调后的模型保存与加载
  • 积分商城网站开发/域名收录
  • 网站全屏视频怎么做/免费网站推广软件
  • 禅城网站建设公司/网络推广服务