鸿蒙HarmonyOS ArkTS UI分层设计在PC端的应用

仓库地址: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 - 按钮组件

@Component
export struct 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') return 80;
    if (this.btnSize === 'large') return 160;
    return 120;
  }

  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 - 文本组件

@Component
export struct 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') return 32;
    if (this.textType === 'subheading') return 20;
    if (this.textType === 'caption') return 12;
    return 14;
  }

  getFontWeight(): number {
    if (this.textType === 'heading') return FontWeight.Bold;
    if (this.textType === 'subheading') return FontWeight.Medium;
    return FontWeight.Normal;
  }
}

设计要点

  • 支持四种文本样式:heading、subheading、body、caption
  • 统一管理字体大小和字重
  • 支持自定义颜色和对齐方式

二、分子层组件设计

分子层由多个原子组件组合而成,形成具有特定功能的组件。

2.1 SearchBoxMolecule - 搜索框组件

import { ButtonAtom } from '../atoms/ButtonAtom';

@Component
export struct SearchBoxMolecule {
  @State inputValue: 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';

@Component
export struct 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';

@Component
export struct 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';

@Component
export struct 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';

@Component
export struct MainTemplate {
  @State searchKeyword: string = '';
  @State searchResults: 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');
  }

  @Builder
  buildSearchResults() {
    // 搜索结果展示
  }

  @Builder
  buildFooter() {
    // 页脚
  }

  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 组件命名规范

层级命名规则示例
原子层名称 + AtomButtonAtom, TextAtom
分子层名称 + MoleculeSearchBoxMolecule, CardMolecule
组织层名称 + OrganismHeaderOrganism, FeatureSectionOrganism
模板层名称 + TemplateMainTemplate, DetailTemplate

6.2 设计原则

  1. 单一职责:每个组件只负责一个功能
  2. 可复用性:组件应设计为可在多个场景使用
  3. 可配置性:通过参数提供灵活的配置选项
  4. 解耦合:组件之间尽量独立,通过参数传递数据

6.3 ArkTS 注意事项

在HarmonyOS ArkTS中使用分层设计时需要注意:

注意事项说明
属性命名避免与基类属性冲突(如 size, onClick, align)
类型安全使用显式接口定义数据结构
状态管理使用 @State 管理组件内部状态
生命周期合理使用组件生命周期方法

七、总结

分层设计是一种强大的UI架构模式,通过将UI拆分为原子、分子、组织和模板四个层次,可以显著提高代码的:

  1. 复用性:原子组件可以在多个页面复用
  2. 可维护性:组件职责单一,易于测试和修改
  3. 可扩展性:新增功能只需添加新组件
  4. 一致性:统一的设计语言和组件规范

相关文件

  • [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)

参考资料

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

红目香薰

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值