如何在Lit框架中使用adoptedStyleSheets?
Lit中adoptedStyleSheets使用指导
Lit底层默认会自动处理组件样式的挂载,我们给组件配置static styles属性时,框架内部已经自动通过adoptedStyleSheets把样式挂载到组件Shadow DOM上,日常开发不需要手动操作,仅特殊场景需要手动调用相关能力,具体用法如下:
场景1:给单个Lit组件追加额外共享样式
如果需要给单个组件追加全局通用的公共样式(比如全局按钮、字体规则),可以在组件的生命周期钩子中手动操作adoptedStyleSheets数组,示例代码如下:
import { LitElement, html, css } from 'lit'; // 定义全局共享样式 const globalBaseStyle = css` :host { font-family: system-ui, sans-serif; box-sizing: border-box; } .common-btn { border-radius: 4px; padding: 6px 12px; border: none; cursor: pointer; } `; class MyCustomComponent extends LitElement { firstUpdated() { // 注意:需要先展开原有的样式表数组再追加新样式,避免覆盖组件本身定义的static styles this.renderRoot.adoptedStyleSheets = [ ...this.renderRoot.adoptedStyleSheets, globalBaseStyle.styleSheet ]; } render() { return html` <button class="common-btn">使用共享样式的按钮</button> `; } }
场景2:批量给多个Shadow Root挂载样式
可以使用Lit封装的adoptStyles工具方法,该方法兼容低版本浏览器的样式挂载逻辑,适合批量操作的场景,示例代码如下:
import { adoptStyles } from 'lit'; import { globalBaseStyle } from './base-style.js'; // 假设有3个需要挂载公共样式的组件实例 const componentList = [componentA, componentB, componentC]; componentList.forEach(component => { // 第一个参数为Shadow Root实例,第二个参数为css标签生成的样式对象数组 adoptStyles(component.renderRoot, [globalBaseStyle]); });
注意事项
- 不要直接覆盖
adoptedStyleSheets数组,必须先展开原有数组再追加新样式,否则会丢失组件本身定义的样式 - 关闭Shadow DOM的Lit组件(配置了
shadowRoot: null)不要使用该能力,否则样式会挂载到全局文档,造成样式污染 - 动态更新样式时需要替换整个
adoptedStyleSheets数组才会触发浏览器重绘,直接修改数组内单个样式表内容不会生效
内容的提问来源于stack exchange,提问作者王子1986
相关产品推荐
相关产品推荐

