preact源码分析:createVNode

核心方法 createVNode, 用于创建 vnode
更新于: 2021-12-19 12:57:29

方法的作用

Create a VNode (used internally by Preact)

 

let vnodeId = 0;

export function createVNode(type, props, key, ref, original) {
  // V8 seems to be better at detecting type shapes if the object is allocated from the same call site
  // Do not inline into createElement and coerceToVNode!
  const vnode = {
    type,
    props,
    key,
    ref,
    _children: null,
    _parent: null,
    _depth: 0,
    _dom: null,
    // _nextDom must be initialized to undefined b/c it will eventually
    // be set to dom.nextSibling which can return `null` and it is important
    // to be able to distinguish between an uninitialized _nextDom and
    // a _nextDom that has been set to `null`
    _nextDom: undefined,
    _component: null,
    _hydrating: null,
    constructor: undefined,
    _original: original == null ? ++vnodeId : original,
  };

  // Only invoke the vnode hook if this was *not* a direct copy:
  if (original == null && options.vnode != null) options.vnode(vnode);

  return vnode;
}

分析

  1. 返回一个  vnode,实际上是一个  object,具有一些初始化的 key
  2. 有一个 options.vnode,可以自己实现,如果有自己实现的部分,则相当于在现有的 vnode上面添加属性