外观
自定义主题
约 778 字大约 3 分钟
2025-10-31
uView Next 的样式基于「设计变量」构建,颜色、行高、圆角都不在组件里写死,而是统一引用 styles/variable.scss 中的别名。理解变量体系后,主题定制与组件样式覆盖都只需改变量或加一个 class。
变量体系
| 层级 | 文件 | 作用 |
|---|---|---|
| ① Token | styles/theme.scss、styles/theme-dark.scss | 原始值,全部带 !default,支持编译期覆盖 |
| ② CSS 变量 | styles/dark.scss | .theme-dark 下重定义 --un-*,实现运行时换肤 |
| ③ 别名 | styles/variable.scss | $xxx: var(--un-xxx, $un-xxx),组件只引用这一层 |
命名规则:
- Token 与 CSS 变量统一使用
un-前缀($un-color-primary/--un-color-primary),别名去掉前缀($color-primary)。 - 语义色五档:
base(无后缀)、light、lighter、dark、disabled。 - 中性色三组:
text-color-*、border-color-*、bg-color-*(背景灰阶 1~7,数字越大越深)。 - 行高与圆角不随主题变化,深色主题只重定义颜色。
方法一:编译时变量覆盖
适用于项目初始化时确定主题风格的场景。Token 都带 !default,在组件库加载前重定义同名变量即可生效,通常写在项目根目录的 uni.scss 中:
// 主色
$un-color-primary: #1677ff;
$un-color-primary-light: #d4e7ff;
$un-color-primary-lighter: #e6f0ff;
$un-color-primary-dark: #0e5cd6;
// 文本色
$un-text-color: #1f1f1f;
$un-text-color-secondary: #5c5c5c;
$un-text-color-muted: #999999;
$un-text-color-placeholder: #aaaaaa;
// 边框色
$un-border-color: #d9d9d9;
$un-border-color-light: #e5e5e5;
$un-border-color-lighter: #eeeeee;
// 背景色(1~7 由浅到深)
$un-bg-color: #ffffff;
$un-bg-color-2: #f5f5f5;
$un-bg-color-disabled: #f0f0f0;
// 行高与圆角
$un-line-base: 21px;
$un-radius-base: 4px;
$un-radius-lg: 6px;完整的变量清单见 styles/theme.scss,示例中未列出的项会继续使用默认值。
方法二:运行时动态修改
适用于运行中切换主题(如浅色 / 深色、品牌换肤)。由于别名是 var(--un-xxx, $un-xxx),在根节点覆盖 CSS 变量即可,组件样式会自动更新:
.theme-custom {
--un-color-primary: #19be6b;
--un-color-primary-lighter: #e7f9ef;
--un-bg-color: #ffffff;
--un-bg-color-2: #f5f5f5;
--un-text-color: #1f1f1f;
--un-radius-base: 8px;
}<view class="theme-custom">
<un-button type="primary" text="主题按钮"></un-button>
</view>组件库内置了深色主题,引入 styles/dark.scss 后给根节点加 .theme-dark 即可。
自定义组件默认样式
uView 的组件统一采用 app-and-page 样式隔离模式,页面与全局中同名的 class 可以作用于组件内部,优先级为 页面 > 组件 > 全局。因此业务侧可以直接覆盖组件的默认样式,无需修改组件源码。样式隔离的完整规则见官方文档:class 样式隔离策略。
1. 覆盖组件根节点
在组件上写 class 或 style,直接作用于组件根节点:
<template>
<un-button class="my-button" style="margin-top: 10px" text="按钮"></un-button>
</template>
<style lang="scss">
.my-button {
height: 48px;
border-radius: 24px;
}
</style>2. 覆盖组件内部元素
组件内部使用 BEM 命名(如 un-tag__text、un-select__option-text),在页面中写同名 class 即可覆盖,页面样式优先级高于组件样式:
<style lang="scss">
.un-tag__text {
font-weight: bold;
}
.un-select__option-text {
color: #ff9900;
}
</style>