在上一篇文章中,深入的了解了 props 相关的一些内容,还涉及到了一点点组件编译相关的。

Solid 之旅 —— 为什么 props 被解构后会导致响应式丢失

通过这篇文章,主要了解两个方面:

先从一个最简单的案例来说,不添加任何响应式数据,先了解组件编译后的内容。

Solid 官方提供了 playground 可以进行调试

Solid Playground

组件编译

import { render } from "solid-js/web";

function Counter() {
  return (
    <button type="button">
      click
    </button>
  );
}

render(() => <Counter />, document.getElementById("app")!);

编译后

import { template as _$template } from "solid-js/web";
import { createComponent as _$createComponent } from "solid-js/web";
var _tmpl$ = /*#__PURE__*/_$template(`<button type=button>click`);
import { render } from "solid-js/web";
function Counter() {
  return _tmpl$();
}
render(() => _$createComponent(Counter, {}), document.getElementById("app"));

我们一个个来看,<Counter> 组件内的 html 标签被使用一个名叫 template 函数调用了

template

来看一下 template 函数的源码:

export function template(html, isCE, isSVG) {
  let node;
  const create = () => {
    const t = document.createElement("template");
    t.innerHTML = html;
    return isSVG ? t.content.firstChild.firstChild : t.content.firstChild;
  };
  // backwards compatible with older builds
  const fn = isCE
    ? () => untrack(() => document.importNode(node || (node = create()), true))
    // 返回一个克隆的节点,然后再对其进行操作
    : () => (node || (node = create())).cloneNode(true);
  fn.cloneNode = fn;
  return fn;
}

这个函数的主要目的就是根据 html 字符串创建一个模板元素。