Webcomponents css类在插槽中不可用



假设我有以下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,我看不到样式。然而,我只是在html上添加了一个普通的p标签,颜色正确地变成了红色

但在我的插槽中,我似乎无法通过index.html中定义的css类。有人能告诉我为什么吗?

这是根据Web组件Shadow DOM规范的预期行为。

在您的代码中

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

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

最新更新