Stencil.js 呈现插槽内容,如果 render() returns null 则事件

Stencil.js renders slot content, event if the render() returns null

我有一个 Stencil.JS 个组件:

import {Component, Prop, h} from '@stencil/core';

@Component({
   tag: 'my-comp',
   styleUrl: 'my-comp.css',
   // shadow: true
})

export class MyComp {
   @Prop() active: boolean = false;
   render() {
      return this.active ? <div>
         <slot></slot>
      </div> : null;
   }
}

当我以这种方式使用组件时,我预计插槽的内容不会呈现:

<my-comp>
   <p>I'm hidden!</p>
</my-comp>

而且,当 "shadow" 在组件装饰器中设置为 true 时,它​​实际上按预期工作。 但是,当禁用阴影 DOM 时,无论 this.active.

的值如何,组件都会显示插槽的内容

我有一种感觉,我不明白渲染是如何与插槽一起工作的。你能给我解释一下吗?如果您知道如何在不以编程方式隐藏插槽内容的情况下解决此问题,我将不胜感激。

查看文档:
https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_templates_and_slots

SLOT 元素只能用于阴影DOM,当用于光线DOM(或任何DOM)时它们是未知标签因此显示内容

接受的答案不正确。 Stencil 绝对支持 <slot>,即使在非 shadow 组件中也是如此。这就是内容投影在 Stencil 中的工作方式。

有几点注意事项; <slot> 元素本身并不是由 Stencil 在 lightdom 组件中实际渲染的,它们仅用作 Stencil 放置子项的位置标记。

此外,根据这个问题,不支持有条件地渲染插槽:
https://github.com/ionic-team/stencil/issues/399

我们在 Stencil lightdom 组件中使用了 <slot>,并且为了这个目的,基本上退回到在 <slot> 周围的包装器上切换 display: none。这并不理想,但它确实有效。