如何选择自定义元素的子元素所在的位置?

How to choose where children of a custom element will be located?

您好,我有一个自定义 web 组件,我想决定将上层(父)元素插入的子元素放在哪里。

使用我的自定义组件的上 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>

如何选择在 React 中将 Angular 或 props.children 中的 ng-content 之类的内容放在哪里?我正在构建一个自定义的 webcomponent 库。谢谢

您可以使用 slots 来显示 parent 方向的内容。此外,您可以通过命名插槽来组织它。

这适用于 Angular 和 Content Projection

您可以给这些 ng-content 个名字。

正如@FloWy所说,你可以使用<slot>

对于原生自定义元素,您需要使用阴影 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>