ReactElement源码剖析

媒介

ReactElement并不像之前所谈的PureComponent和Component那样被频仍的显现运用,但我预计他应该是在react暴露出的api中被挪用最为频仍的,关于此看完背面便知。ReactElement中暴露出createElement,createFactory,cloneElement,isValidElement,cloneAndReplaceKey五个要领,统共400来行代码,比较轻易。

文章中若有不当之处,迎接交换指导。react版本
16.8.2。在源码增加的解释在github
react-source-learn

jsx与ReactElement

在运用react时我们经常在render要领返回(函数组件的话多是直接返回)类似下面的代码。

<Wrap>
    <h1>测试</h1>
    <List />
    <Footer />
</Wrap>

这就是传说中的jsx语法,js并没有这类东西,这类语法终究都会被转换成规范的js。请看下图:

《ReactElement源码剖析》

发明这些jsx被转化成了js,每一个组件或许html标签转化后都是挪用React.createElement(type, config, children)。这里的React.createElement实在就是ReactElement.createElement。由此能够推想,ReactElement暴露的要领是挪用最频仍的。

createElement剖析

createElement的主要挪用以下:

createElement -> ReactElement

当然在dev下另有些其他的挪用。

createElement源码以下

/**
 * Create and return a new ReactElement of the given type.
 * See https://reactjs.org/docs/react-api.html#createelement
 */

 // jsx转换后挪用的要领
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
    // 将config中的数据放到props中,  key,ref,__self,__source除外
    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.
  // children天生
  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
  // 复制默许props
  if (type && type.defaultProps) {
    const defaultProps = type.defaultProps;
    for (propName in defaultProps) {
      if (props[propName] === undefined) {
        props[propName] = defaultProps[propName];
      }
    }
  }
  // 这里不然从props中读key, 和ref, 然则里边事实上就是没有的
  if (__DEV__) {
    if (key || ref) {
      const displayName =
        typeof type === 'function'
          ? type.displayName || type.name || 'Unknown'
          : type;
      if (key) {
        // displayName: 组织函数名, 或标署名 a , h1
        defineKeyPropWarningGetter(props, displayName);
      }
      if (ref) {
        defineRefPropWarningGetter(props, displayName);
      }
    }
  }
  // 就一个一般对象
  return ReactElement(
    type,
    key,
    ref,
    self,
    source,
    ReactCurrentOwner.current,
    props,
  );
}

createElement主要做了以下事变:

  1. 将特别属性从config掏出, 如key,ref,__self,__source
  2. 将非特别属性挂到props上,比方上边谁人图中的className
  3. 将第三个及以后的参数挂到props.children上,多个是天生数组,单个是直接挂
  4. 默许值defaultProps的处置惩罚
  5. 将处置惩罚好的数据作为参数挪用ReactElement并返回

ReactElement源码以下

// 这个函数做的事异常简朴, 就是将传进来的参放到一个对象里边返回
 // 个中source, self在临盆形式没有返回
 // owner 变成了_owner
 // 开辟形式下, 返回了将source, self也挂在了返回的对象上, 变成了_source, _self
const ReactElement = function(type, key, ref, self, source, owner, props) {
  const element = {
    // This tag allows us to uniquely identify this as a React Element
    $$typeof: REACT_ELEMENT_TYPE, // 一个Symobol或许16进制数,
                                  //用于示意ReactElement范例

    // Built-in properties that belong on the element
    type: type,
    key: key,
    ref: ref,
    props: props,

    // Record the component responsible for creating this element.
    _owner: owner,
  };

  // 这里边放了self, source
  if (__DEV__) {
    // The validation flag is currently mutative. We put it on
    // an external backing store so that we can freeze the whole object.
    // This can be replaced with a WeakMap once they are implemented in
    // commonly used development environments.
    element._store = {};

    // To make comparing ReactElements easier for testing purposes, we make
    // the validation flag non-enumerable (where possible, which should
    // include every environment we run tests in), so the test framework
    // ignores it.
    Object.defineProperty(element._store, 'validated', {
      configurable: false,
      enumerable: false,
      writable: true,
      value: false,
    });
    // self and source are DEV only properties.
    Object.defineProperty(element, '_self', {
      configurable: false,
      enumerable: false,
      writable: false,
      value: self,
    });
    // Two elements created in two different places should be considered
    // equal for testing purposes and therefore we hide it from enumeration.
    Object.defineProperty(element, '_source', {
      configurable: false,
      enumerable: false,
      writable: false,
      value: source,
    });

    // Object.freeze() 要领能够凝结一个对象。一个被凝结的对象再也不能被修正;
    // 凝结了一个对象则不能向这个对象增加新的属性,不能删除已有属性,不能修正该对象已有属性的可罗列性、
    // 可设置性、可写性,以及不能修正已有属性的值。
    // 另外,凝结一个对象后该对象的原型也不能被修正。freeze() 返回和传入的参数雷同的对象。


    // Object.seal()要领关闭一个对象,阻挠增加新属性并将一切现有属性标记为不可设置。当前属性的值只需可写就能够转变。

    // Object.preventExtensions()要领让一个对象变的不可扩大,也就是永久不能再增加新的属性。


    if (Object.freeze) {
      Object.freeze(element.props);
      Object.freeze(element);
    }
  }

  return element;
};

他几乎是没做什么事变的,就是将传入的参数放到一个对象返回,加了一个$$typeof标识ReactElement。个中运用了一个Object.freeze要领,这个要领不太经常使用,意义是凝结一个对象,使其不能被修正,相干的另有Object.seal,Object.preventExtensions,能够找些文档了解下。

小结下ReactElement.createElement

ReactElement.createElement终究返回的是一个一般的对象,对参数进行了校验,提取等操纵。上面为剖析dev下的代码,去看一下会发明也是比较风趣的。

createFactory,cloneAndReplaceKey,cloneElement和isValidElement

createFactory

export function createFactory(type) {
  const factory = createElement.bind(null, type);
  // Expose the type on the factory and the prototype so that it can be
  // easily accessed on elements. E.g. `<Foo />.type === Foo`.
  // This should not be named `constructor` since this may not be the function
  // that created the element, and it may not even be a constructor.
  // Legacy hook: remove it
  factory.type = type;
  return factory;

  // 如许
  // return function factory(...args) {
  //   return createElement(type, ...args);
  // }
}

这个要领很简朴,是对createElement的一个柯里化的操纵。

cloneAndReplaceKey

// 克隆reactElement并将key改成新key
export function cloneAndReplaceKey(oldElement, newKey) {
  const newElement = ReactElement(
    oldElement.type,
    newKey,
    oldElement.ref,
    oldElement._self,
    oldElement._source,
    oldElement._owner,
    oldElement.props,
  );

  return newElement;
}

从旧的ReactElement对象天生一个新的,将key属性替换成新的

isValidElement

/**
 * Verifies the object is a ReactElement.
 * See https://reactjs.org/docs/react-api.html#isvalidelement
 * @param {?object} object
 * @return {boolean} True if `object` is a ReactElement.
 * @final
 */
export function isValidElement(object) {
  // 照样很严谨的
  return (
    typeof object === 'object' &&
    object !== null &&
    object.$$typeof === REACT_ELEMENT_TYPE
  );
}

推断一个值是否是ReactElement,运用了建立时挂上去的$$typeof

cloneElement

// 和createElement基础雷同
export function cloneElement(element, config, children) {
  invariant(
    !(element === null || element === undefined),
    'React.cloneElement(...): The argument must be a React element, but you passed %s.',
    element,
  );

  let propName;

  // Original props are copied
  const props = Object.assign({}, element.props);

  // Reserved names are extracted
  let key = element.key;
  let ref = element.ref;
  // Self is preserved since the owner is preserved.
  const self = element._self;
  // Source is preserved since cloneElement is unlikely to be targeted by a
  // transpiler, and the original source is probably a better indicator of the
  // true owner.
  const source = element._source;

  // Owner will be preserved, unless ref is overridden
  let owner = element._owner;

  if (config != null) {
    if (hasValidRef(config)) {
      // Silently steal the ref from the parent.
      ref = config.ref;
      owner = ReactCurrentOwner.current;
    }
    if (hasValidKey(config)) {
      key = '' + config.key;
    }

    // Remaining properties override existing props
    let defaultProps;
    if (element.type && element.type.defaultProps) {
      defaultProps = element.type.defaultProps;
    }
    for (propName in config) {
      if (
        hasOwnProperty.call(config, propName) &&
        !RESERVED_PROPS.hasOwnProperty(propName)
      ) {
        if (config[propName] === undefined && defaultProps !== undefined) {
          // Resolve default props
          props[propName] = defaultProps[propName];
        } else {
          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];
    }
    props.children = childArray;
  }

  return ReactElement(element.type, key, ref, self, source, owner, props);
}

这段代码和createElement异常类似,不同之处在于他是返回第一个参数ReactElement的一个副本。他的key,ref等属性和供应的需要被克隆的ReactElement的雷同,props也是本来的props,然则能够传入config修正。

/packages/react.js小结

至此,/packages/react.js总的最最主要的东西已剖析完了,关于hooks等其他内容就像不剖析了。这里边的代码实在并没有做什奇异的事变,ReactElement只是建立和操纵一般对象,Component和PureComponent只是定义了两个简朴的组织函数,定义了几个要领,个中比较主要的应该是updater,然则到目前为止还没有看到他的身影。这些东西都不触及dom操纵,是平台无关的。

这里代码都比较好明白,背面就将进入深水区了,要最先研讨ReactDOM里边的render了。加油!

    原文作者:Bigbear
    原文地址: https://segmentfault.com/a/1190000018828296
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞