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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM