简体   繁体   English

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

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

I have a Stencil.JS components:我有一个 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;
   }
}

I expect that content of the slot is not rendering when I use the component in this manner:当我以这种方式使用组件时,我希望插槽的内容不会呈现:

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

And, actually it works as expected, when "shadow" set to true in Component decorator.而且,实际上它按预期工作,当“阴影”在组件装饰器中设置为 true 时。 But, when the shadow DOM is disabled, component shows the content of slot regardless of the value of this.active.但是,当禁用 shadow DOM 时,无论 this.active 的值如何,组件都会显示 slot 的内容。

I have a feeling that I don't understand how the render works with slots.我有一种感觉,我不明白渲染是如何与插槽一起工作的。 Could you please explain it to me?你能给我解释一下吗? I would really appreciate If you know how to work-around this issue without hiding the slot content programatically.如果您知道如何在不以编程方式隐藏插槽内容的情况下解决此问题,我将非常感激。

The accepted answer is incorrect.接受的答案是不正确的。 Stencil absolutely supports <slot> , even in non- shadow components. Stencil 绝对支持<slot> ,即使在非shadow组件中也是如此。 That is how content projection works in Stencil.这就是 Stencil 中内容投影的工作原理。

There are a few caveats;有一些警告; the <slot> elements themselves are not actually rendered by Stencil in lightdom components, they serve only as location markers for where Stencil places children. <slot>元素本身实际上并不是由 Stencil 在 lightdom 组件中渲染的,它们仅用作 Stencil 放置子元素的位置标记。

Additionally, pursuant to this question, conditionally rendering slots is not supported:此外,根据这个问题,不支持条件渲染槽:
https://github.com/ionic-team/stencil/issues/399 https://github.com/ionic-team/stencil/issues/399

We use <slot> in Stencil lightdom components, and have essentially fallen back on toggling display: none on a wrapper around the <slot> for this purpose.我们在 Stencil lightdom 组件中使用<slot> ,并且基本上已经退回到切换display: none为此目的在<slot>周围的包装器上display: none It's not ideal, but it works.这并不理想,但它有效。

See the documentation:请参阅文档:
https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_templates_and_slots https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_templates_and_slots

SLOT elements can only be used in shadowDOM, when used in lightDOM (or any DOM) they are unknown tags thus display the contents SLOT 元素只能在 shadowDOM 中使用,当在 lightDOM(或任何 DOM)中使用时,它们是未知标签,因此显示内容

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM