zoukankan      html  css  js  c++  java
  • React函数组件和类组件的区别

    定义组件有两个要求:

    1. 组件名称必须以大写字母开头
    2. 组件的返回值只能有一个根元素

    函数组件

    function Welcome (props) {
      return <h1>Welcome {props.name}</h1>
    }
    ReactDOM.render(<Welcome name='react' />, document.getElementById('root'));
    1. 函数组件接收一个单一的 props 对象并返回了一个React元素

    类组件

    class Welcome extends React.Component {
      render() {
        return (
          <h1>Welcome { this.props.name }</h1>
        );
      }
    }
    ReactDOM.render(<Welcome name='react' />, document.getElementById('root'));

    1. 无论是使用函数或是类来声明一个组件,它决不能修改它自己的 props
    2. 所有 React 组件都必须是纯函数,并禁止修改其自身 props 。
    3. React是单项数据流,父组件改变了属性,那么子组件视图会更新。
    4. 属性 props 是外界传递过来的,状态 state 是组件本身的,状态可以在组件中任意修改
    5. 组件的属性和状态改变都会更新视图。

    区别

    函数组件和类组件当然是有区别的,而且函数组件的性能比类组件的性能要高,因为类组件使用的时候要实例化,而函数组件直接执行函数取返回结果即可。为了提高性能,尽量使用函数组件。

    区别函数组件类组件
    是否有 this 没有
    是否有生命周期 没有
    是否有状态 state 没有
  • 相关阅读:
    Python异步任务模块之-celery
    Atom 编辑器侧边栏忽略隐藏文件
    判断字符串是否为回文 python
    python 命令行工具 fire
    Appium自动化测试-iOS
    视频转换工具ffmpeg
    nodejs顺序执行shell
    Jenkins 邮箱配置及问题解决
    mac配置php
    appium镜像设置
  • 原文地址:https://www.cnblogs.com/plBlog/p/14333858.html
Copyright © 2011-2022 走看看