如何在NativeScript V8 Angular中按主题设置SCSS变量实现暗黑模式
NativeScript Angular 暗黑模式适配方案(基于现有SCSS变量体系)
方案一:使用CSS自定义属性(推荐)
这种方式利用NativeScript切换主题时自动添加的根元素类(ns-light/ns-dark),结合CSS变量实现动态样式切换,无需修改现有组件的SCSS引用逻辑。
- 修改
_variables.scss,定义主题对应的CSS变量
// 浅色主题默认变量 :root { --bg: #fff; --text-color: #333; --button-bg: #007bff; // 其他自定义变量... } // 深色主题覆盖变量 .ns-dark { --bg: #121212; --text-color: #fff; --button-bg: #1a73e8; // 对应深色主题的其他变量... }
- 在
_app-common.scss和组件SCSS中替换为CSS变量
原来用$bg的地方,改成var(--bg),示例如下:
// _app-common.scss @import './variables'; Page { background-color: var(--bg); } Label { color: var(--text-color); } Button { background-color: var(--button-bg); color: var(--text-color); }
组件SCSS示例:
// my-component.component.scss @import '../variables'; .my-custom-container { background-color: var(--bg); padding: 16px; }
- 结合
Theme.setMode()完成切换
切换主题时,Theme.setMode()会自动给根元素添加/移除ns-dark/ns-light类,CSS变量会自动生效:
import { Theme } from '@nativescript/theme'; // 切换主题方法 toggleTheme() { const currentMode = Theme.getMode(); const newMode = currentMode === 'light' ? 'dark' : 'light'; Theme.setMode(newMode as any); // 可选:保存主题设置到本地存储 localStorage.setItem('selectedTheme', newMode); } // 初始化时恢复保存的主题 ngOnInit() { const savedTheme = localStorage.getItem('selectedTheme') || 'light'; Theme.setMode(savedTheme as any); }
方案二:SCSS混合宏预编译主题样式
如果偏好纯SCSS变量方案,可以通过混合宏预编译不同主题的样式规则,同样利用NativeScript的主题类实现切换。
- 修改
_variables.scss,定义主题映射和混合宏
// 定义各主题的变量集合 $themes: ( light: ( bg: #fff, text-color: #333, button-bg: #007bff ), dark: ( bg: #121212, text-color: #fff, button-bg: #1a73e8 ) ); // 生成主题样式的混合宏 @mixin apply-theme($property, $variable-key) { // 默认浅色主题样式 #{$property}: map-get(map-get($themes, light), $variable-key); // 深色主题样式 .ns-dark & { #{$property}: map-get(map-get($themes, dark), $variable-key); } }
- 在通用样式和组件中使用混合宏
// _app-common.scss @import './variables'; Page { @include apply-theme(background-color, bg); } Button { @include apply-theme(background-color, button-bg); @include apply-theme(color, text-color); }
组件SCSS示例:
// my-component.component.scss @import '../variables'; .my-custom-container { @include apply-theme(background-color, bg); }
- 主题切换逻辑同方案一
调用Theme.setMode()切换时,根元素的主题类会触发对应的预编译样式生效。
注意事项
- 确保
@NativeScript/Theme已正确安装并配置,切换主题时根元素会自动添加ns-light/ns-dark类。 - 如果使用CSS变量方案,无需修改现有组件对
_variables.scss的引用,只需替换变量使用方式。 - 初始化主题时,建议从本地存储读取用户之前的选择,避免每次启动都重置为默认。
内容的提问来源于stack exchange,提问作者Jonas Sch
相关产品推荐
相关产品推荐

