使用 JS 创建的模板标记在附加到 Web 组件内的阴影时不会出现

Template tag created using JS doesn't appear when appended to shadow inside web component

我希望以下代码创建一个包含 div 且其中包含文本 "Hi" 的元素。

元素出现在检查器中,但屏幕上看不到任何文本。

当我将模板从 template 更改为 div 时,文本出现了。我在这里做错了什么?

class MyComponent extends HTMLElement {
    constructor() {
        super()

        const shadowRoot = this.attachShadow({ mode: 'open' })
        const template = document.createElement('template')
        const div = document.createElement('div')

        div.innerHTML = 'Hi'
        template.appendChild(div)

        shadowRoot.appendChild(template.content)
    }
}
customElements.define('my-component', MyComponent)

<template>是特殊元素。

通过其 content 添加一些 HTML 元素 属性:

template.content.appendChild(div)

或通过 innerHTML 添加 HTML 代码 属性:

template.innerHTML = '<div>Hi</div>'

我同意@Supersharp 的回答。这是不需要 <template>.

的替代解决方案

class MyComponent extends HTMLElement {
    constructor() {
        super()
        const div = document.createElement('div')
        div.innerHTML = 'Hi'
        this.attachShadow({ mode: 'open' }).appendChild(div)
    }
}
customElements.define('my-component', MyComponent)
<my-component></my-component>

或者你可以只使用 shadowRoot 的 innerHTML:

class MyComponent extends HTMLElement {
    constructor() {
        super()
        this.attachShadow({ mode: 'open' }).innerHTML = "<div>Hi</div>";
    }
}
customElements.define('my-component', MyComponent)
<my-component></my-component>