简体   繁体   English

基于类在 Stencil 组件上设置宿主元素样式

[英]Style host element on Stencil component based on class

In Stencil when you have set shadow: true , styling the host element is as follows在 Stencil 中设置shadow: true后,宿主元素的样式如下

:host {
    color: red;
}

This works.这行得通。 But now I have the following component但现在我有以下组件

@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>;
    }
}

in which I add the is-test class to the host element.我在其中将is-test类添加到宿主元素。 Now, to apply styling based on that class I added the following现在,要根据该类应用样式,我添加了以下内容

:host {
    color: red;

    &.is-test {
        background-color: green;
    }
}

I see is-test class on my-component element, but the background-color: green style is not applied.我在my-component元素上看到is-test类,但未应用background-color: green样式。 I must be doing something wrong here, any help would be appreciated!我一定是在这里做错了什么,任何帮助将不胜感激!

You can use :host() :您可以使用:host()

:host {
    color: red;
}

:host(.is-test) {
    background-color: green;
}

By the way: If you want to set the class (or any attribute) on the host element, you can use the <Host> functional component :顺便说一句:如果你想在宿主元素上设置类(或任何属性),你可以使用<Host>功能组件

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

// ...

render() {
    return <Host class="is-test"><div>Test</div></Host>;
}

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

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