Styling 文档的底部有一节介绍如何使用 CSS 变量:
在本例中,我们定义了一个名为 --app-primary-color 的 CSS 变量,其颜色设置为 #488aff。此示例中的 :root 选择器是一个 CSS 伪选择器,它在项目的根元素(通常为 <html>)上定义变量,以便可以在您的应用中使用该变量。
所以如果你有一个这样的按钮组件:
@Component({ tag: 'my-button', styleUrl: 'button.css' })
export class Button {
render() {
return <div class="button"><slot /></div>;
}
}
下面是button.css:
.button {
background: var(--primary-color, tomato);
color: var(--light-color, white);
display: block;
padding: 1em 2em;
border-radius: 0.2em;
font-family: sans-serif;
text-align: center;
text-transform: uppercase;
}
然后,您可以通过在 CSS 中的某处设置变量来覆盖所有按钮颜色:
:root {
--primary-color: mediumseagreen;
}
CSS 变量也可以使用 Javascript 设置,它们甚至可以由 Stencil 为旧版浏览器填充。
JSFiddle 示例:http://jsfiddle.net/5fv9r6e1/
顺便说一句,在你的组件装饰器中你也可以设置shadow: true 来启用Shadow DOM,然后你可以使用:host 选择器并且在这个例子中不需要包装div:
@Component({ tag: 'my-button', styleUrl: 'button.css', shadow: true })
export class Button {
render() {
return <slot />;
}
}
css:
:host {
background: var(--primary-color, tomato);
color: var(--light-color, white);
display: block;
padding: 1em 2em;
border-radius: 0.2em;
font-family: sans-serif;
text-align: center;
text-transform: uppercase;
}
Ionic 4 经常使用这个概念,因此可能值得看看他们的 Stencil 组件:https://github.com/ionic-team/ionic/tree/master/core/src/components