无论如何要知道一个命名插槽包含多少个孩子?在我的 Stencil 组件中,我的渲染函数中有这样的东西:
<div class="content">
<slot name="content"></slot>
</div>
Run Code Online (Sandbox Code Playgroud)
我想要做的是根据插槽内有多少孩子对 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';
}
}
Run Code Online (Sandbox Code Playgroud)
但是,即使我将项目插入插槽,这也总是报告 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>);
}
}Run Code Online (Sandbox Code Playgroud)