Web 组件 - 包装 child 个元素
Web Components - wrap child elements
我有一个可以有 children 的网络组件。在 JS 上看到它希望将其当前 children 包装在模态标签中(已经有 child)。
我目前有:
class Modal extends HTMLElement {
connectedCallback() {
// Wrap current children inside of dialog element
}
}
customElements.define("modal-component", Modal);
<modal-component>
<p> Lorem impsum </p>
</modal-component>
<!-- I want the logic in connectedCallback() to produce this with the p tag now being wrapped inside dialog -->
<modal-component>
<dialog>
<span class="close">×</span>
<p> Lorem impsum </p>
</dialog>
</modal-component>
我试着在 connectedCallback
里面写这个但是 this.innerHTML
的值是 ''
即使有 children
this.innerHTML = `<dialog><span class="close">×</span>${this.innerHTML}</dialog>`;
我尝试过使用插槽,但当我的 Modal
组件必须将多个 children 放入一个插槽时,该功能似乎只涵盖一对一注入。
最好的方法是什么?
使用插槽可以插入多个 children:
connectedCallback() {
this.attachShadow( { mode: 'open' } )
.innerHTML = `<span class="close">×</span>
<slot></slot>`
}
或者,如果您不想使用 <slot>
,则需要确保在访问 innerHTML
属性 时解析自定义元素的内容。
这可以通过 setTimeout
or requestAnimationFrame
或在解析 HTML 代码后定义自定义元素来实现(如果可能的话):
<custom-element>...</custome-element>
<script>
customElements.define( 'custom-element', ... )
</script>
我有一个可以有 children 的网络组件。在 JS 上看到它希望将其当前 children 包装在模态标签中(已经有 child)。
我目前有:
class Modal extends HTMLElement {
connectedCallback() {
// Wrap current children inside of dialog element
}
}
customElements.define("modal-component", Modal);
<modal-component>
<p> Lorem impsum </p>
</modal-component>
<!-- I want the logic in connectedCallback() to produce this with the p tag now being wrapped inside dialog -->
<modal-component>
<dialog>
<span class="close">×</span>
<p> Lorem impsum </p>
</dialog>
</modal-component>
我试着在 connectedCallback
里面写这个但是 this.innerHTML
的值是 ''
即使有 children
this.innerHTML = `<dialog><span class="close">×</span>${this.innerHTML}</dialog>`;
我尝试过使用插槽,但当我的 Modal
组件必须将多个 children 放入一个插槽时,该功能似乎只涵盖一对一注入。
最好的方法是什么?
使用插槽可以插入多个 children:
connectedCallback() {
this.attachShadow( { mode: 'open' } )
.innerHTML = `<span class="close">×</span>
<slot></slot>`
}
或者,如果您不想使用 <slot>
,则需要确保在访问 innerHTML
属性 时解析自定义元素的内容。
这可以通过 setTimeout
or requestAnimationFrame
或在解析 HTML 代码后定义自定义元素来实现(如果可能的话):
<custom-element>...</custome-element>
<script>
customElements.define( 'custom-element', ... )
</script>