Bootstrap

【React】最新版本18 源码遨游(一) createElement()

React源码遨游

今天新开的专栏主要围绕着React源码进行学习,切入口主要围绕着React的顶层API(即React)。

createElement()

createElment() 隶属于顶层ApiReact/src/ReactElement.js中。

首先我们看一下创建组件的代码,然后逐句分析一下。

export function createElement(type, config, children) {
   
  let propName;

  // Reserved names are extracted
  const props = {
   };

  let key = null;
  let ref = null;
  let self = null;
  let source = null;

  if (config != null) {
   
    if (hasValidRef(config)) {
   
      ref = config.ref;

      if (__DEV__) {
   
        warnIfStringRefCannotBeAutoConverted(config);
      }
    }
    if (hasValidKey(config)) {
   
      key = '' + config.key;
    }

    self = config.__self === undefined ? null : config.__self;
    source = config.__source === undefined ? null : config.__source;
    // Remaining properties are added to a new props object
    for (propName in config) {
   
      if (
        hasOwnProperty.call(config, propName) &&
        !RESERVED_PROPS.hasOwnProperty(propName)
      ) {
   
        props[propName] = config[propName];
      }
    }
  }

  // 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;
  }

  // Resolve default props
  if (type && type.defaultProps) {
   
    const defaultProps = type.defaultProps;
    for (propName in defaultProps) {
   
      if (props[propName] === undefined) {
   
        props[propName] = defaultProps[propName];
      }
    }
  }
  if (__DEV__) {
   
    if (key || ref) {
   
      const displayName =
        typeof type === 'function'
          ? type.displayName || type.name || 'Unknown'
          : type;
      if (key) {
   
      

悦读

道可道,非常道;名可名,非常名。 无名,天地之始,有名,万物之母。 故常无欲,以观其妙,常有欲,以观其徼。 此两者,同出而异名,同谓之玄,玄之又玄,众妙之门。

;