基于类的 Stencil 组件上的样式宿主元素

Jea*_*eri 2 css web-component stenciljs

在 Stencil 中设置后shadow: true,样式宿主元素如下

:host {
    color: red;
}
Run Code Online (Sandbox Code Playgroud)

这有效。但现在我有以下组件

@Component({
    tag: 'my-component',
    styleUrl: 'my-component.scss',
    shadow: true
})
export class MyComponent {
    @Element() host: HTMLElement;

    render() {
        this.host.classList.add('is-test');
        return <div>Test</div>;
    }
}
Run Code Online (Sandbox Code Playgroud)

在其中我将is-test类添加到宿主元素。现在,为了应用基于该类的样式,我添加了以下内容

:host {
    color: red;

    &.is-test {
        background-color: green;
    }
}
Run Code Online (Sandbox Code Playgroud)

is-testmy-component元素上看到类,但未background-color: green应用样式。我一定在这里做错了什么,任何帮助将不胜感激!

Tho*_*mas 10

您可以使用:host()

:host {
    color: red;
}

:host(.is-test) {
    background-color: green;
}
Run Code Online (Sandbox Code Playgroud)

顺便说一句:如果你想设置的主机元件上的类(或任何属性),就可以使用<Host>功能组件

import { Host } from '@stencil/core';

// ...

render() {
    return <Host class="is-test"><div>Test</div></Host>;
}
Run Code Online (Sandbox Code Playgroud)