Webcomponents css class 在插槽中不可用

Webcomponents css class not usable in slot

假设我有以下 css 文件:

.testClass{
    color:red;
}

以及以下 index.html 文件:

<html>
  <head>
    <meta charset="utf-8">
    <title>Portal Demo</title>
    <link rel="stylesheet" href="test.css">
    <script type="module" src="../build/portal-app.js"></script>
    <style>
      p {
        border: solid 1px blue;
        padding: 8px;
      }
    </style>
  </head>
  <body>
  <i class="fa fa-times"></i>
    <portal-app>
      <p>This is child cosntent</p>
    </portal-app>
  </body>
</html>

portal-app 中我有以下代码:

   import  'sdk-button'
@customElement('portal-app')
export class PortalApp extends LitElement {
    render() {
        return html`
      ${this.renderWidget()} 
    `;
    }

    renderWidget() {
        import("./views/my-test-element");
        return html`
<i class="fa fa-times"></i>
        <sdk-icon-button text="hello marc"><p slot="icon" class="testClass">hello</p></sdk-icon-button>
    `;
    }
}

declare global {
    interface HTMLElementTagNameMap {
        'portal-app': PortalApp;
    }
}

当我 运行 这个 .p 标签的颜色不是 red 并且我看不到样式。但是我只是添加了一个普通的 p 标签到 html 颜色正确地变成了红色。

但似乎在我的插槽中我无法通过 index.html 中定义的 css class 谁能告诉我为什么?

这是 Web Components Shadow DOM specifications 的预期行为。

在你的代码中

<p slot="icon" class="testClass">hello</p>

此模板是 PortalApp Web 组件的一部分。这意味着此标记位于 Portal App Web 组件的 Shadow DOM 中。没有 css 来自外部 (index.html) 的样式可以应用于此标记。反之亦然,即不会 CSS 从组件泄漏到组件外部