Stencil 组件上的样式主机元素基于 class
Style host element on Stencil component based on class
在 Stencil 中设置 shadow: true
后,主机元素的样式如下
:host {
color: red;
}
这行得通。但是现在我有以下组件
@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>;
}
}
其中我将 is-test
class 添加到宿主元素。现在,要根据 class 应用样式,我添加了以下
:host {
color: red;
&.is-test {
background-color: green;
}
}
我在 my-component
元素上看到 is-test
class,但未应用 background-color: green
样式。我一定是在这里做错了什么,任何帮助将不胜感激!
您可以使用 :host()
:
:host {
color: red;
}
:host(.is-test) {
background-color: green;
}
顺便说一句:如果你想在宿主元素上设置 class(或任何属性),你可以使用 the <Host>
functional component:
import { Host } from '@stencil/core';
// ...
render() {
return <Host class="is-test"><div>Test</div></Host>;
}
在 Stencil 中设置 shadow: true
后,主机元素的样式如下
:host {
color: red;
}
这行得通。但是现在我有以下组件
@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>;
}
}
其中我将 is-test
class 添加到宿主元素。现在,要根据 class 应用样式,我添加了以下
:host {
color: red;
&.is-test {
background-color: green;
}
}
我在 my-component
元素上看到 is-test
class,但未应用 background-color: green
样式。我一定是在这里做错了什么,任何帮助将不胜感激!
您可以使用 :host()
:
:host {
color: red;
}
:host(.is-test) {
background-color: green;
}
顺便说一句:如果你想在宿主元素上设置 class(或任何属性),你可以使用 the <Host>
functional component:
import { Host } from '@stencil/core';
// ...
render() {
return <Host class="is-test"><div>Test</div></Host>;
}