首页 > 解决方案 > Web 组件 - 包装子元素

问题描述

我有一个可以有孩子的网络组件。并且在 JS 上看到它希望它将其当前的孩子包装在一个模态标签(已经有一个孩子)中。

我目前有:

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">&times;</span>
         <p> Lorem impsum </p>
    </dialog> 
</modal-component>

我试着在里面写这个,但即使有孩子,connectedCallback它的价值this.innerHTML也是如此''

this.innerHTML = `<dialog><span class="close">&times;</span>${this.innerHTML}</dialog>`;

Modal我尝试过使用插槽,但是当我的组件必须将多个子项放入一个插槽时,该功能似乎只涵盖一对一的注入。

这样做的最佳方法是什么?

标签: web-component

解决方案


使用插槽,您可以插入多个孩子:

connectedCallback() {
     this.attachShadow( { mode: 'open' } )
         .innerHTML = `<span class="close">&times;</span>
                 <slot></slot>`
}

或者,如果您不想使用<slot>,则需要确保在访问innerHTML属性时解析自定义元素的内容。

这可以通过setTimeoutrequestAnimationFrame来实现,或者通过在解析 HTML 代码后定义自定义元素(如果可能的话):

<custom-element>...</custome-element>
<script>
  customElements.define( 'custom-element', ... )
</script>

推荐阅读