React源码解析:createElement

228 阅读1分钟

1. JSX转换成js:

<div id='div' key='key'>demo</div>
转换为:
React.createElement("div", {
 id: "div",
 key: "key"
}, "demo");

属性放在第二个参数,第二个参数是个对象,都会加在这个对象里面给他。第三个参数在 React 中称为 children ,也就是标签内容。

属性放在第二个参数,第二个参数是个对象,都会加在这个对象里面给他。第三个参数在 React 中称为 children ,也就是标签内容。

<div id='div' key='key'>
  <span>spanDemo</span>
</div>
转换为:
React.createElement("div", {
  id: "div",
  key: "key"
}, React.createElement("span", null, "spanDemo"));

2. createElement介绍:

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 (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) {
        defineKeyPropWarningGetter(props, displayName);
      }
      if (ref) {
        defineRefPropWarningGetter(props, displayName);
      }
    }
  }
  return ReactElement(
    type,
    key,
    ref,
    self,
    source,
    ReactCurrentOwner.current,
    props,
  );
}

createElement组件有三个参数 type ,config, children。

  1. type:节点类型,若是原生节点,就是字符串,若是自己声明的组件,就是class的 component或function的component。
  2. config:写在jsx标签上的元素的属性值对对象,这些属性可以通this.props.*来调用。
  3. children:内容或者子节点。

友情链接:react源码解析