仓库地址:https://atomgit.com/feng8403000/hongmeng61fencengsheji
示例效果:
引言
在现代UI开发中,代码的可维护性和复用性是至关重要的。HarmonyOS 6.1提供了强大的ArkUI框架,支持声明式UI开发。本文将介绍如何使用分层设计模式构建高质量的HarmonyOS应用。
什么是分层设计
分层设计(Atomic Design)是一种UI组件架构方法论,将UI拆分为不同层次的组件:
| 层级 | 名称 | 说明 | 示例 |
|---|---|---|---|
| 原子层 | Atoms | 最基础的UI元素 | 按钮、文本、图标 |
| 分子层 | Molecules | 原子组件的组合 | 搜索框、卡片 |
| 组织层 | Organisms | 分子组件的组合 | 头部、列表、表单 |
| 模板层 | Templates | 页面布局框架 | 主页面、详情页 |
分层架构优势
┌─────────────────────────────────────────────────────────────┐ │ 模板层 (Templates) │ │ MainTemplate - 页面布局框架 │ ├─────────────────────────────────────────────────────────────┤ │ 组织层 (Organisms) │ │ HeaderOrganism FeatureSectionOrganism │ │ ┌──────────┐ ┌─────────────────┐ │ │ │分子层组件│ │ 分子层组件 │ │ │ └──────────┘ └─────────────────┘ │ ├─────────────────────────────────────────────────────────────┤ │ 分子层 (Molecules) │ │ SearchBoxMolecule CardMolecule │ │ ┌──────────┐ ┌─────────────────┐ │ │ │原子层组件│ │ 原子层组件 │ │ │ └──────────┘ └─────────────────┘ │ ├─────────────────────────────────────────────────────────────┤ │ 原子层 (Atoms) │ │ ButtonAtom TextAtom │ │ ┌────────┐ ┌────────┐ │ │ │ArkUI原生│ │ArkUI原生│ │ │ │ 组件 │ │ 组件 │ │ │ └────────┘ └────────┘ │ └─────────────────────────────────────────────────────────────┘设计优势
| 特性 | 说明 |
|---|---|
| 高复用性 | 原子组件可在多个页面复用 |
| 易维护性 | 组件职责单一,易于测试和修改 |
| 可扩展性 | 新增功能只需添加新组件 |
| 一致性 | 统一的设计语言和组件规范 |
| 团队协作 | 多人协作时减少代码冲突 |
一、原子层组件设计
原子层是UI的最小构建块,包含最基础的UI元素。
1.1 ButtonAtom - 按钮组件
@Componentexportstruct ButtonAtom{label:string='';btnType:'primary'|'secondary'|'danger'='primary';btnSize:'small'|'medium'|'large'='medium';onTap:()=>void=()=>{};build(){Button(this.label).width(this.getWidth()).height(this.getHeight()).backgroundColor(this.getBgColor()).fontColor('#ffffff').fontSize(this.getFontSize()).fontWeight(FontWeight.Bold).borderRadius(this.getRadius()).border({width:this.getBorderWidth(),color:this.getBorderColor()}).onClick(this.onTap);}getWidth():number{if(this.btnSize==='small')return80;if(this.btnSize==='large')return160;return120;}getBgColor():string{if(this.btnType==='secondary')return'rgba(255,255,255,0.1)';if(this.btnType==='danger')return'#ef4444';return'#22c55e';}// ... 其他方法省略}设计要点:
- 支持三种类型:primary(主要)、secondary(次要)、danger(危险)
- 支持三种尺寸:small、medium、large
- 通过独立方法管理样式,便于维护和扩展
1.2 TextAtom - 文本组件
@Componentexportstruct TextAtom{content:string='';textType:'heading'|'subheading'|'body'|'caption'='body';textColor:string='#ffffff';textAlignment:TextAlign=TextAlign.Start;build(){Text(this.content).fontSize(this.getFontSize()).fontWeight(this.getFontWeight()).fontColor(this.textColor).textAlign(this.textAlignment);}getFontSize():number{if(this.textType==='heading')return32;if(this.textType==='subheading')return20;if(this.textType==='caption')return12;return14;}getFontWeight():number{if(this.textType==='heading')returnFontWeight.Bold;if(this.textType==='subheading')returnFontWeight.Medium;returnFontWeight.Normal;}}设计要点:
- 支持四种文本样式:heading、subheading、body、caption
- 统一管理字体大小和字重
- 支持自定义颜色和对齐方式
二、分子层组件设计
分子层由多个原子组件组合而成,形成具有特定功能的组件。
2.1 SearchBoxMolecule - 搜索框组件
import{ButtonAtom}from'../atoms/ButtonAtom';@Componentexportstruct SearchBoxMolecule{@StateinputValue:string='';onSearch:(keyword:string)=>void=()=>{};build(){Row({space:10}){TextInput({placeholder:'请输入搜索关键词...',text:this.inputValue}).width('75%').height(48).backgroundColor('rgba(255,255,255,0.08)').fontColor('#ffffff').placeholderColor('rgba(255,255,255,0.4)').borderRadius(12).padding({left:20,right:20}).onChange((value:string)=>{this.inputValue=value;});ButtonAtom({label:'搜索',btnType:'primary',btnSize:'medium',onTap:()=>{this.onSearch(this.inputValue);}});}.width('100%').height(60);}}设计要点:
- 组合 TextInput 和 ButtonAtom
- 内部管理输入状态
- 通过回调函数向外传递搜索事件
2.2 CardMolecule - 卡片组件
import{TextAtom}from'../atoms/TextAtom';@Componentexportstruct CardMolecule{title:string='';description:string='';icon:string='';tag:string='';tagColor:string='#22c55e';build(){Stack({alignContent:Alignment.TopStart}){Column({space:15}){Row({space:10}){Text(this.icon).fontSize(32);if(this.tag){Text(this.tag).fontSize(12).fontColor(this.tagColor).backgroundColor(this.getBgColorWithOpacity()).padding({left:8,right:8,top:2,bottom:2}).borderRadius(4);}}.width('100%');Column({space:8}){TextAtom({content:this.title,textType:'subheading'});TextAtom({content:this.description,textType:'body',textColor:'rgba(255,255,255,0.6)'});}.width('100%');}.width('100%').padding(20);Row(){Rect().width(40).height(3).fill(this.tagColor);}.width('100%').padding({bottom:20,left:20});}.width('100%').height(180).backgroundColor('rgba(255,255,255,0.05)').borderRadius(16).border({width:1,color:'rgba(255,255,255,0.1)'});}// ... 其他方法省略}设计要点:
- 组合图标、标签、标题、描述
- 使用 Stack 实现多层布局
- 支持自定义标签颜色
三、组织层组件设计
组织层由多个分子组件组合而成,形成页面的独立区域。
3.1 HeaderOrganism - 头部导航组件
import{TextAtom}from'../atoms/TextAtom';import{ButtonAtom}from'../atoms/ButtonAtom';import{SearchBoxMolecule}from'../molecules/SearchBoxMolecule';@Componentexportstruct HeaderOrganism{onSearch:(keyword:string)=>void=()=>{};build(){Column({space:20}){Row(){Column({space:5}){TextAtom({content:'HarmonyOS 6.1',textType:'caption',textColor:'rgba(255,255,255,0.5)'});TextAtom({content:'分层设计示例',textType:'heading'});}.flexGrow(1);Row({space:10}){ButtonAtom({label:'登录',btnType:'secondary',btnSize:'small'});ButtonAtom({label:'注册',btnType:'primary',btnSize:'small'});}}.width('100%').height(80);SearchBoxMolecule({onSearch:this.onSearch});}.width('100%').padding({left:30,right:30,top:30});}}设计要点:
- 组合品牌标识、操作按钮、搜索框
- 作为页面顶部的完整区域
3.2 FeatureSectionOrganism - 功能区域组件
import{TextAtom}from'../atoms/TextAtom';import{CardMolecule}from'../molecules/CardMolecule';@Componentexportstruct FeatureSectionOrganism{build(){Column({space:20}){Column({space:5}){TextAtom({content:'核心能力',textType:'caption',textColor:'#22c55e'});TextAtom({content:'HarmonyOS 6.1 新特性',textType:'subheading'});TextAtom({content:'探索最新的HarmonyOS功能,体验更强大的智能终端体验',textType:'body',textColor:'rgba(255,255,255,0.5)'});}.width('100%');Grid(){GridItem(){CardMolecule({title:'原子化服务',description:'无需安装,一键直达。全新的服务形态,让应用触手可及。',icon:'⚛️',tag:'新特性',tagColor:'#22c55e'});}// ... 其他卡片省略}.columnsTemplate('1fr 1fr').rowsTemplate('1fr 1fr').columnsGap(20).rowsGap(20).width('100%').height(400);}.width('100%').padding({left:30,right:30,top:40});}}设计要点:
- 使用 Grid 布局展示多个卡片
- 包含标题区域和内容区域
四、模板层设计
模板层是页面的最高层级,组合所有组织层组件形成完整页面。
4.1 MainTemplate - 主页面模板
import{HeaderOrganism}from'../organisms/HeaderOrganism';import{FeatureSectionOrganism}from'../organisms/FeatureSectionOrganism';import{TextAtom}from'../atoms/TextAtom';@Componentexportstruct MainTemplate{@StatesearchKeyword:string='';@StatesearchResults:Array<string>=[];build(){Scroll(){Column({space:0}){HeaderOrganism({onSearch:(keyword:string)=>{this.handleSearch(keyword);}});FeatureSectionOrganism();if(this.searchResults.length>0){this.buildSearchResults();}this.buildFooter();}.width('100%');}.width('100%').height('100%').backgroundColor('#0f172a');}@BuilderbuildSearchResults(){// 搜索结果展示}@BuilderbuildFooter(){// 页脚}handleSearch(keyword:string){// 搜索逻辑}}设计要点:
- 组合所有组织层组件
- 管理页面级状态
- 提供可滚动的页面布局
五、完整项目结构
entry/src/main/ets/ ├── components/ │ ├── atoms/ # 原子层 │ │ ├── ButtonAtom.ets │ │ └── TextAtom.ets │ ├── molecules/ # 分子层 │ │ ├── SearchBoxMolecule.ets │ │ └── CardMolecule.ets │ ├── organisms/ # 组织层 │ │ ├── HeaderOrganism.ets │ │ └── FeatureSectionOrganism.ets │ └── templates/ # 模板层 │ └── MainTemplate.ets └── pages/ └── Index.ets # 入口页面六、分层设计最佳实践
6.1 组件命名规范
| 层级 | 命名规则 | 示例 |
|---|---|---|
| 原子层 | 名称 + Atom | ButtonAtom, TextAtom |
| 分子层 | 名称 + Molecule | SearchBoxMolecule, CardMolecule |
| 组织层 | 名称 + Organism | HeaderOrganism, FeatureSectionOrganism |
| 模板层 | 名称 + Template | MainTemplate, DetailTemplate |
6.2 设计原则
- 单一职责:每个组件只负责一个功能
- 可复用性:组件应设计为可在多个场景使用
- 可配置性:通过参数提供灵活的配置选项
- 解耦合:组件之间尽量独立,通过参数传递数据
6.3 ArkTS 注意事项
在HarmonyOS ArkTS中使用分层设计时需要注意:
| 注意事项 | 说明 |
|---|---|
| 属性命名 | 避免与基类属性冲突(如 size, onClick, align) |
| 类型安全 | 使用显式接口定义数据结构 |
| 状态管理 | 使用 @State 管理组件内部状态 |
| 生命周期 | 合理使用组件生命周期方法 |
七、总结
分层设计是一种强大的UI架构模式,通过将UI拆分为原子、分子、组织和模板四个层次,可以显著提高代码的:
- 复用性:原子组件可以在多个页面复用
- 可维护性:组件职责单一,易于测试和修改
- 可扩展性:新增功能只需添加新组件
- 一致性:统一的设计语言和组件规范
相关文件
- [ButtonAtom.ets](file:///d:/HarmonyOSProject/MyApplication_PC0613/entry/src/main/ets/components/atoms/ButtonAtom.ets)
- [TextAtom.ets](file:///d:/HarmonyOSProject/MyApplication_PC0613/entry/src/main/ets/components/atoms/TextAtom.ets)
- [SearchBoxMolecule.ets](file:///d:/HarmonyOSProject/MyApplication_PC0613/entry/src/main/ets/components/molecules/SearchBoxMolecule.ets)
- [CardMolecule.ets](file:///d:/HarmonyOSProject/MyApplication_PC0613/entry/src/main/ets/components/molecules/CardMolecule.ets)
- [HeaderOrganism.ets](file:///d:/HarmonyOSProject/MyApplication_PC0613/entry/src/main/ets/components/organisms/HeaderOrganism.ets)
- [FeatureSectionOrganism.ets](file:///d:/HarmonyOSProject/MyApplication_PC0613/entry/src/main/ets/components/organisms/FeatureSectionOrganism.ets)
- [MainTemplate.ets](file:///d:/HarmonyOSProject/MyApplication_PC0613/entry/src/main/ets/components/templates/MainTemplate.ets)
- [Index.ets](file:///d:/HarmonyOSProject/MyApplication_PC0613/entry/src/main/ets/pages/Index.ets)
参考资料:
- HarmonyOS UI设计分层流程官方文档