Skip to the content.

react源码阅读笔记:一、关于 React.createElement

函数定义

export function createElement(type, config, children) { ... }
  1. React.createElement干了点啥

    创建了一个ReactElement类型的对象

    ReactElement的构造函数需要一些必须的参数

    return ReactElement(
        type,
        key,
        ref,
        self,
        source,
        ReactCurrentOwner.current,
        props,
      ) 
    

    关于ReactCurrentOwner.current的说明

    Keeps track of the current owner. The current owner is the component who should own any components that are currently being constructed. ···················································

    追踪当前所有者 当前所有者是所有的正在构建的组件的根组件

    ReactElement 是啥????

  2. 创建过程是啥样子的

    1. 关于type

      type可能是一个 原生的 html 标签字符串,也有可能是一个ReactElement,或者React Fragment 类型的对象

    2. 关于config

      1. 四个特殊的属性

        1. key
        2. ref
        3. self
        4. source

        如果config中存在有效的这四个属性,则这些属性会被传递到ReactElement的构造函数中,否则传递的值是null

      2. 其他属性

        config中的其他属性会被保存到props对象中,然后传递到ReactElement的构造函数中

    3. 关于children

      createElement函数的参数个数是有可能大于个的,从第三个参数后的所有参数都是childrenReact会将所有的children元素合并为一个children数组,并挂载到props上面。

      // Children can be more than one argument, and those are transferred onto
        // the newly allocated props object.
        const childrenLength = arguments.length - 2;
        if (childrenLength === 1) {
          props.children = children;
        } else if (childrenLength > 1) {
          const childArray = Array(childrenLength);
          for (let i = 0; i < childrenLength; i++) {
            childArray[i] = arguments[i + 2];
          }
          if (__DEV__) {
            if (Object.freeze) {
              Object.freeze(childArray);
            }
          }
          props.children = childArray;
        }
      
    4. 处理元素的默认属性

      对于typeReactElement,或者React Fragment的情况,元素会自带一些默认属性,这些默认属性也要挂载到props上去