您好,我有一个自定义的webcomponent,我想决定在哪里放置由上部(父)元素插入的子元素。
使用我的自定义组件的上层html元素文件:
<custom-component>
<custom-component2></custom-component2>
</custom-component>描述自定义组件内部结构的文件:
<h5>title</h5>
<p>paragraph</p>DOM中的结果:
<custom-component>
<custom-component2></custom-component2>
<h5>title</h5>
<p>paragraph</p>
</custom-component>我想要的:
<custom-component>
<h5>title</h5>
<p>paragraph</p>
<custom-component2></custom-component2>
</custom-component>如何选择将诸如Angular中的ng-content或React中的props.children之类的内容放在哪里?我正在构建一个自定义的webcomponent库。谢谢
发布于 2020-05-20 16:53:37
发布于 2020-05-20 23:05:15
正如@FloWy所说,你可以使用<slot>。
对于本机自定义元素,您需要使用Shadow DOM。
customElements.define( 'custom-component', class extends HTMLElement {
constructor() {
super()
var sh = this.attachShadow( { mode: 'open' } )
sh.innerHTML = `<h5>Title</h5>
<p>Paragraph</p>
Slot content: <slot></slot>`
}
} )<custom-component>
<custom-component2>Child element</custom-component2>
</custom-component1>
https://stackoverflow.com/questions/61908882
复制相似问题