【问题标题】:How to determine number of children in a slot如何确定插槽中的孩子数量
【发布时间】:2018-12-15 19:35:39
【问题描述】:

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

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

我想要做的是根据插槽内有多少孩子来设置不同的 div.content 样式。如果插槽中没有子元素,则 div.content 的 style.display='none',否则,我将一堆样式应用于 div.content 以使子元素正确显示在屏幕上。

我试过了:

  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。

【问题讨论】:

    标签: slots stenciljs


    【解决方案1】:

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

    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>);
      }
    }

    【讨论】:

    • 谢谢你,Gil,我没想到会在宿主元素中找到所有插槽内容。现在我知道了这一点,我可以更新我的代码来做我需要的事情。
    猜你喜欢
    • 2021-09-23
    • 2014-05-02
    • 1970-01-01
    • 2022-07-16
    • 2023-02-03
    • 2017-10-28
    • 2023-01-20
    • 1970-01-01
    • 2022-12-17
    相关资源
    最近更新 更多