我有两个最小的HTMLElements:一个AppRoot和一个SubElement。元素的innerHTML是通过lit-html的render和html模板函数生成的。
AppRoot的HTML模板是一个包含两个段落的div:一个显示message属性的文本,另一个实例化SubElement并向其传递字符串。
SubElement的超文本标记语言模板只是传递的字符串。
我希望呈现的HTML看起来像这样:
<div>
<p>AppRoot's message</p>
<p>The string passed to SubElement</p>
</div>但实际上它只是SubElement的呈现模板:
The string passed to SubElement为什么SubElement的模板在呈现时会替换AppRoot的模板?我已经尝试过更改标签(用div、段落括起来),但没有效果。
你可以在下面找到源代码。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script src="./index.js" type="module"></script>
<app-root></app-root>
</body>
</html>import { render, html } from './node_modules/lit-html/lit-html.js';
class SubElement extends HTMLElement {
constructor(message) {
super();
this.message = message;
}
connectedCallback() {
this.innerHTML = render(this.template(), document.body);;
}
template() {
return html`
${this.message}
`;
}
}
customElements.define('sub-element', SubElement);
class AppRoot extends HTMLElement {
constructor() {
super();
this.message = "I am root!";
}
connectedCallback() {
this.innerHTML = render(this.template(), document.body);
}
template() {
return html`
<div>
<p>${this.message}</p>
<p>${new SubElement("I am not root!")}</p>
</div>
`;
}
}
customElements.define('app-root', AppRoot);发布于 2021-07-26 21:11:49
render的第二个参数是应该在其中呈现模板的容器。每个组件当前将模板结果呈现到文档正文,并覆盖先前呈现的结果。
connectedCallback() {
this.innerHTML = render(this.template(), document.body);
}您应该考虑在组件本身中使用shadow DOM或render。
connectedCallback() {
render(this.template(), this);
}https://stackoverflow.com/questions/68519499
复制相似问题