Lightning Web Components 组件样式(四)

要将样式与组件进行绑定,需要创建一个同名的样式文件,这样样式将会自动应用到组件
在组件中定义的样式的作用域是属于组件的,这样允许组件可以在不同的上下文中可以复用,
可以阻止其他组件的样式的复写

css 作用域例子

  • 重要说明
    一个组件的文件夹和文件名是骆驼的情况下,myComponent,myComponent.html,和myComponent.css。
    在HTML标记中,camelCase映射到kebab-case。当组件呈现时,<template>标记将替换为标记包含组件的
    命名空间
  • 一个简单demo

    demo 说明,包含了两个组件,cssParent 以及cssChild 每个组件包含一个<p>标签,cssParent.css 样式定义xx-large p
    样式,样式只应用到parent p 标签,而不是在child 中的

    标签

cssParent.js

 
import { LightningElement } from 'lwc';
export default class CssParent extends LightningElement {}

cssParent.html


<template>
  <p>To Do List</p>
  <example-css-child></example-css-child>
</template>
 
 

cssParent.css

p {
    font-size: xx-large;
}

cssChild.js

import { LightningElement } from 'lwc';
export default class CssChild extends LightningElement {}

cssChild.html

<template>
     <p>To Do Item</p>
</template>
 
 

cssChild.css

/*
:host {
    display: block;
    background: whitesmoke;
}
*/
 
 

父组件应用样式到child 组件,这个可以通过元素样式的方式

/* cssParent.css */
p {
    font-size: xx-large;
}
example-css-child {
    display: block;
    background: whitesmoke;
}
 
 

子组件样式的应用,可以通过:host 配置样式,以及类似parent 的样式配置

/* cssChild.css */
:host {
    display: block;
    background: whitesmoke;
}
 

同时对于组件我们可以添加<slot></slot> 方便的进行内容填充

css 的支持以及对于性能的影响

  • 一些不支持的css 选择器
    :host-context()
    ::slotted
    不支持id 选择器
  • 对于性能的影响
    每个选择器都有自己作用域链,所以传递给的每个复合表达式:host()都会扩展到多个选择器中。这种转换增加了生成的CSS的大小和复杂性。
    为了确保CSS封装,每个元素都有一个额外的属性,这也增加了渲染时间

参考资料

https://lwc.dev/guide/reference#component-bundles
https://lwc.dev/guide/composition#pass-markup-into-slots

posted on 2019-06-03 12:47  荣锋亮  阅读(946)  评论(0编辑  收藏  举报

导航