Lightning Web Components 组件样式(四)

要将样式与组件进行绑定,须要建立一个同名的样式文件,这样样式将会自动应用到组件
在组件中定义的样式的做用域是属于组件的,这样容许组件能够在不一样的上下文中能够复用,
能够阻止其余组件的样式的复写css

css 做用域例子

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

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

    标签ide

cssParent.js性能

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

cssParent.htmlui


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

cssParent.cssspa

p {
    font-size: xx-large;
}

cssChild.jscode

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

cssChild.htmlcomponent

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

cssChild.csshtm

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

父组件应用样式到child 组件,这个能够经过元素样式的方式ip

/* 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

相关文章
相关标签/搜索