一、前言
很多鸿蒙开发项目写到后期,都会出现同一个致命问题:页面UI风格混乱、重复代码满天飞、组件无法复用。
新建十个页面,就有十种按钮样式、十种弹窗动画、十种输入框规则,没有统一规范,后期迭代、改样式、换主题需要改几百处代码,维护彻底崩盘。
商用级项目和练手Demo的核心差距,就是是否拥有一套自研基础组件库。
本篇从零搭建一套企业级鸿蒙通用组件库,包含:组件设计规范、全局样式抽离、高复用基础组件、组件解耦、属性配置、事件外抛、统一导出架构,所有代码可直接落地生产项目。
二、商用组件库核心设计规范
封装自定义组件,绝对不能“写死样式、写死业务”,必须遵循五大企业规范:
1. 配置驱动(属性优先)
所有样式、状态、文本、显隐,全部通过入参控制,不写死在组件内部,一套组件适配多业务场景。
2. 业务解耦
基础组件只负责UI展示与基础交互,不写任何业务逻辑,业务事件全部向外抛出,由页面层处理。
3. 状态全覆盖
组件必须兼容:默认、禁用、加载、报错、选中、置灰等常用状态,避免页面重复适配。
4. 样式统一托管
颜色、圆角、间距、字号全部抽离全局常量,杜绝代码硬编码,支持一键换主题。
5. 可扩展可嵌套
支持自定义插槽、自定义样式覆盖,满足通用场景+特殊定制场景。
三、前置准备:全局样式常量体系
组件库搭建第一步,不是写组件,是统一全局设计规范。
3.1 全局颜色常量 Color.ets
// common/constants/Color.etsexport const Color = { // 主色 PRIMARY: '#007AFF', PRIMARY_LIGHT: '#E8F3FF', PRIMARY_DARK: '#0062CC', // 功能色 SUCCESS: '#34C759', WARNING: '#FF9500', DANGER: '#FF3B30', INFO: '#909399', // 文本色 TEXT_MAIN: '#1D2129', TEXT_SUB: '#666666', TEXT_DESC: '#999999', // 背景色 BG_WHITE: '#FFFFFF', BG_GRAY: '#F5F7FA', BG_DARK: '#EEEEEE', // 边框 BORDER: '#E5E6EB', // 禁用 DISABLED: '#C8C9CC'} as const
3.2 全局尺寸常量 Size.ets
// common/constants/Size.etsexport const Size = { // 圆角 RADIUS_SM: 4, RADIUS_MD: 8, RADIUS_LG: 12, RADIUS_XL: 16, // 间距 PADDING_SM: 8, PADDING_MD: 12, PADDING_LG: 16, // 按钮高度 BUTTON_HEIGHT_SM: 32, BUTTON_HEIGHT_MD: 40, BUTTON_HEIGHT_LG: 48, // 输入框高度 INPUT_HEIGHT: 48, // 字号 FONT_SM: 12, FONT_MD: 14, FONT_LG: 16, FONT_XL: 18} as const
四、核心组件一:商用通用按钮(多状态、多类型)
按钮是项目使用频率最高的组件,统一封装后彻底解决样式混乱问题。
4.1 组件完整源码
// components/common/AppButton.etsimport { Color } from '../../common/constants/Color'import { Size } from '../../common/constants/Size'// 按钮类型枚举export enum ButtonTheme { PRIMARY = 'primary', DEFAULT = 'default', DANGER = 'danger', TEXT = 'text'}@Componentexport struct AppButton { // 基础属性 @Param title: string = '' @Param theme: ButtonTheme = ButtonTheme.PRIMARY @Param disabled: boolean = false @Param loading: boolean = false @Param width: Length = '100%' @Param height: Length = Size.BUTTON_HEIGHT_LG // 点击事件 @Param onClick?: () => void // 动态背景色 get bgColor(): ResourceColor { if (this.disabled || this.loading) return Color.DISABLED switch (this.theme) { case ButtonTheme.PRIMARY: return Color.PRIMARY case ButtonTheme.DANGER: return Color.DANGER case ButtonTheme.DEFAULT: return Color.BG_GRAY default: return Color.BG_WHITE } } // 动态文字色 get textColor(): ResourceColor { if (this.disabled || this.loading) return Color.TEXT_DESC switch (this.theme) { case ButtonTheme.PRIMARY: case ButtonTheme.DANGER: return Color.BG_WHITE case ButtonTheme.TEXT: return Color.PRIMARY default: return Color.TEXT_MAIN } } build() { Button(this.loading ? '' : this.title) .width(this.width) .height(this.height) .fontSize(Size.FONT_MD) .fontColor(this.textColor) .backgroundColor(this.bgColor) .borderRadius(Size.RADIUS_MD) .enabled(!this.disabled && !this.loading) .onClick(() => { if (!this.disabled && !this.loading && this.onClick) { this.onClick() } }) .overlay({ builder: () => { if (this.loading) { LoadingProgress().width(24).height(24).color(Color.BG_WHITE) } } }) }}
4.2 页面调用示例
import { AppButton, ButtonTheme } from '../components/common/AppButton'@Entry@Componentstruct ButtonPage { build() { Column({ space: 15 }) { AppButton({ title: '主要按钮', theme: ButtonTheme.PRIMARY }) AppButton({ title: '默认按钮', theme: ButtonTheme.DEFAULT }) AppButton({ title: '危险按钮', theme: ButtonTheme.DANGER }) AppButton({ title: '文字按钮', theme: ButtonTheme.TEXT }) AppButton({ title: '禁用按钮', disabled: true }) AppButton({ title: '加载中', loading: true }) } .padding(20) .width('100%') .height('100%') .justifyContent(FlexAlign.Center) }}
五、核心组件二:通用输入框(校验、清除、报错适配)
封装带错误提示、一键清除、最大字数、禁用状态的商用输入框,告别重复校验代码。
5.1 组件完整源码
// components/common/AppInput.etsimport { Color } from '../../common/constants/Color'import { Size } from '../../common/constants/Size'@Componentexport struct AppInput { @Param placeholder: string = '请输入内容' @Param value: string = '' @Param errorText: string = '' @Param disabled: boolean = false @Param maxLength: number = 99 @Param onChange?: (val: string) => void @Param onClear?: () => void build() { Column({ space: 6 }) { Row() { TextInput({ text: this.value, placeholder: this.placeholder }) .layoutWeight(1) .height(Size.INPUT_HEIGHT) .fontSize(Size.FONT_MD) .enabled(!this.disabled) .maxLength(this.maxLength) .onChange((val: string) => { this.onChange && this.onChange(val) }) if (this.value.length > 0 && !this.disabled) { Text('×') .fontSize(18) .fontColor(Color.TEXT_DESC) .margin({ right: 10 }) .onClick(() => { this.onClear && this.onClear() }) } } .width('100%') .border({ width: 1, color: this.errorText ? Color.DANGER : Color.BORDER }) .borderRadius(Size.RADIUS_MD) .padding({ left: 12, right: 12 }) // 错误提示文案 if (this.errorText) { Text(this.errorText) .fontSize(Size.FONT_SM) .fontColor(Color.DANGER) .width('100%') } } .width('100%') }}
5.2 页面调用示例
import { AppInput } from '../components/common/AppInput'@Entry@Componentstruct InputPage { @State text: string = '' @State errMsg: string = '' build() { Column({ space: 20 }) { AppInput({ placeholder: '请输入账号', value: this.text, errorText: this.errMsg, onChange: (val: string) => { this.text = val this.errMsg = val.length >= 6 ? '' : '账号长度不能少于6位' }, onClear: () => { this.text = '' this.errMsg = '' } }) } .padding(20) .width('100%') .height('100%') .justifyContent(FlexAlign.Center) }}
六、核心组件三:通用弹窗(全局确认弹窗)
统一项目弹窗样式、动画、按钮逻辑,替代系统原生弹窗,提升产品质感。
6.1 组件完整源码
// components/common/AppDialog.etsimport { Color } from '../../common/constants/Color'import { Size } from '../../common/constants/Size'import { AppButton, ButtonTheme } from './AppButton'@Componentexport struct AppDialog { @Param show: boolean = false @Param title: string = '提示' @Param content: string = '' @Param confirmText: string = '确认' @Param cancelText: string = '取消' @Param onConfirm?: () => void @Param onCancel?: () => void @Param onClose?: () => void build() { if (!this.show) return Stack() { // 遮罩层 ColorBlock(0x000000, 0.6) .width('100%') .height('100%') .onClick(() => this.onClose && this.onClose()) // 弹窗主体 Column({ space: Size.PADDING_LG }) { Text(this.title) .fontSize(Size.FONT_LG) .fontWeight(FontWeight.Medium) .fontColor(Color.TEXT_MAIN) Text(this.content) .fontSize(Size.FONT_MD) .fontColor(Color.TEXT_SUB) .lineHeight(22) Row({ space: Size.PADDING_MD }) { AppButton({ title: this.cancelText, theme: ButtonTheme.DEFAULT, layoutWeight: 1, onClick: () => this.onCancel && this.onCancel() }) AppButton({ title: this.confirmText, theme: ButtonTheme.PRIMARY, layoutWeight: 1, onClick: () => this.onConfirm && this.onConfirm() }) } .width('100%') } .width('85%') .backgroundColor(Color.BG_WHITE) .borderRadius(Size.RADIUS_XL) .padding(Size.PADDING_LG) } .width('100%') .height('100%') }}
七、核心组件四:骨架屏加载组件
替代生硬的Loading转圈,优化页面加载体验,适配列表、卡片页面。
7.1 组件完整源码
// components/common/AppSkeleton.etsimport { Color } from '../../common/constants/Color'import { Size } from '../../common/constants/Size'@Componentexport struct AppSkeleton { @Param rows: number = 3 @Param showAvatar: boolean = true build() { Column({ space: Size.PADDING_MD }) { ForEach(Array.from({ length: this.rows }), () => { Row({ space: Size.PADDING_MD }) { if (this.showAvatar) { Circle() .width(40) .height(40) .fillColor(Color.BG_DARK) .animation({ duration: 1200, curve: Curve.EaseInOut, iterations: -1, playMode: PlayMode.Alternate }) } Column({ space: Size.PADDING_SM }) { Rect().width('60%').height(14).fillColor(Color.BG_DARK).borderRadius(4) Rect().width('100%').height(12).fillColor(Color.BG_DARK).borderRadius(4) } .layoutWeight(1) } }) } .width('100%') .padding(Size.PADDING_MD) }}
八、组件库统一导出配置
新建统一入口文件,简化页面引入,规范项目结构。
// components/common/index.etsexport * from './AppButton'export * from './AppInput'export * from './AppDialog'export * from './AppSkeleton'
九、商用组件封装高频避坑点
禁止组件内写死业务逻辑:组件只做UI,业务逻辑全部外抛,保证通用性;
禁止样式硬编码:所有颜色、尺寸、圆角统一走常量,方便全局换肤;
必须做好状态兼容:禁用、加载、报错状态缺一不可,避免页面重复适配;
事件必须判空:回调事件提前做空判断,避免页面未传参导致报错;
禁止过度封装:通用场景统一封装,特殊场景开放自定义属性,不锁死样式;
严格单向数据流:组件不修改父页面入参,只通过onChange回调通知父页面更新。
十、全文总结
企业级鸿蒙项目的工程化核心,就是组件库标准化。
通过全局样式常量、通用按钮、输入框、弹窗、骨架屏的标准化封装,彻底解决UI混乱、代码冗余、维护困难等问题。
这套组件架构遵循“配置驱动、业务解耦、样式统一、高可复用”的商用标准,可直接落地中大型鸿蒙项目,也是进阶高级鸿蒙工程师的必备核心能力。