web-component - 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">×</span>
<p> Lorem impsum </p>
</dialog>
</modal-component>
我试着在里面写这个,但即使有孩子,connectedCallback
它的价值this.innerHTML
也是如此''
this.innerHTML = `<dialog><span class="close">×</span>${this.innerHTML}</dialog>`;
Modal
我尝试过使用插槽,但是当我的组件必须将多个子项放入一个插槽时,该功能似乎只涵盖一对一的注入。
这样做的最佳方法是什么?
解决方案
使用插槽,您可以插入多个孩子:
connectedCallback() {
this.attachShadow( { mode: 'open' } )
.innerHTML = `<span class="close">×</span>
<slot></slot>`
}
或者,如果您不想使用<slot>
,则需要确保在访问innerHTML
属性时解析自定义元素的内容。
这可以通过setTimeout
或requestAnimationFrame
来实现,或者通过在解析 HTML 代码后定义自定义元素(如果可能的话):
<custom-element>...</custome-element>
<script>
customElements.define( 'custom-element', ... )
</script>
推荐阅读
- regex - 正则表达式去除所有链接,除了包含 xxx 字的链接
- angular - 在 WebStorm 中显示 codelyzer 错误
- python - 选择我希望列中的值具有多个值的行
- qt - 在 QML 中动态更改 Material 主题
- python - 从 Python 列表中提取数据
- java - Spring JMS ActiveMQ 消息传递的咨询主题不起作用
- docker - jenkins-pipeline 中 DockerBuilderPublisher 的 cleanupWithJenkinsJobDelete 有什么用?
- javascript - 点击后JS阻塞按钮,运行代码后解除阻塞
- mysql - 访问被拒绝 localhost mysql
- java - 为什么从@Transactional 方法(Spring boot)返回我的对象时,Hibernate 不能完全解析它?