如何确定插槽中 children 的数量

How to determine number of children in a slot

有没有办法知道一个命名槽包含多少 children?在我的 Stencil 组件中,我的渲染函数中有这样的东西:

<div class="content">
  <slot name="content"></slot>
</div>

我想做的是根据插槽内有多少 children 来设置不同的 div.content 样式。如果插槽中没有children,那么div.content的style.display='none',否则,我有一堆样式应用到div.content使得children 正确显示在屏幕上。

我试过:

  const divEl = root.querySelector( 'div.content' );
  if( divEl instanceof HTMLElement ) {
    const slotEl = divEl.firstElementChild;
    const hasChildren = slotEl && slotEl.childElementCount > 0;
    if( !hasChildren ) {
      divEl.style.display = 'none';
    }
  }

然而,这总是报告 hasChildren = false,即使我将物品插入槽中也是如此。

如果您正在查询宿主元素,您将获得其中的所有开槽内容。这意味着宿主元素的子元素将是所有将被注入到插槽中的内容。 例如,尝试使用以下代码来查看它的实际效果:

import {Component, Element, State} from '@stencil/core';

@Component({
  tag: 'my-component',
  styleUrl: 'my-component.css',
  shadow: true
})
export class MyComponent {
  @Element() host: HTMLElement;
  @State() childrenData: any = {};

  componentDidLoad() {
    let slotted = this.host.children;
    this.childrenData = { hasChildren: slotted && slotted.length > 0, numberOfChildren: slotted && slotted.length };
  }

  render() {
    return (
    <div class="content">
      <slot name="content"></slot>
      <div>
        Slot has children: {this.childrenData.hasChildren ? 'true' : 'false'}
      </div>
      <div>
        Number of children: {this.childrenData.numberOfChildren}
      </div>
    </div>);
  }
}