查看: 71|回复: 1

HarmonyOS NEXT快速开发实战:从环境搭建到Todo App

[复制链接]
发表于 3 小时前 | 显示全部楼层 |阅读模式
HarmonyOS NEXT 是华为面向全场景智能设备的下一代操作系统,其核心开发语言 ArkTS 基于 TypeScript 进化而来,专为声明式 UI 框架 ArkUI 设计。开发者只需描述“界面长什么样”,框架自动处理渲染更新,大幅提升开发效率。本文从环境搭建开始,逐步演示基础组件、页面路由、状态管理,并提供一个完整的待办事项应用(Todo App)示例,帮助你快速上手。

一、开发环境搭建
1. 下载 DevEco Studio:访问华为开发者联盟官网,获取最新版本的 IDE。
2. 安装 Node.js:建议 v18+ 版本,用于构建脚本。
3. 配置 SDK:首次启动时选择“Full SDK”安装,包含 HarmonyOS SDK 和工具链。
4. 开启设备调试:通过 USB 连接或模拟器进行真机/模拟调试。

二、创建新项目
在 DevEco Studio 中,选择 File → New → Create Project → Empty Ability。项目创建向导会自动生成以下核心结构:
  1. entry/
  2. ├── src/main/
  3. │ ├── ets/
  4. │ │ ├── entryability/  # 应用入口
  5. │ │ │ └── EntryAbility.ets
  6. │ │ ├── pages/  # 页面文件
  7. │ │ │ └── Index.ets  # 主页面
  8. │ │ └── App.ets  # 全局应用配置
  9. │ ├── module.json5  # 模块配置
  10. │ └── resources/  # 资源目录
复制代码
其中 entryability 管理应用生命周期,pages 定义 UI 页面,App.ets 用于全局配置。

三、常用 UI 组件快速上手
ArkUI 提供丰富的声明式组件,以下是最常用的基础组件。
3.1 文本与按钮
  1. // Index.ets - 基础组件使用示例
  2. import hilog from '@ohos.hilog';
  3. @Component
  4. struct Index {
  5.   @State message: string = 'Hello HarmonyOS';
  6.   build() {
  7.     Column({ space: 20 }) {
  8.       Text(this.message)
  9.         .fontSize(32)
  10.         .fontWeight(FontWeight.Bold)
  11.         .fontColor('#1A1A1A')
  12.       Button('点击我')
  13.         .width(200)
  14.         .height(50)
  15.         .fontSize(18)
  16.         .backgroundColor('#007DFF')
  17.         .borderRadius(25)
  18.         .onClick(() => {
  19.           this.message = '欢迎来到鸿蒙世界!';
  20.           hilog.info(0, 'Demo', 'Button clicked');
  21.         })
  22.     }
  23.     .width('100%')
  24.     .height('100%')
  25.     .justifyContent(FlexAlign.Center)
  26.     .alignItems(HorizontalAlign.Center)
  27.   }
  28. }
复制代码
3.2 列表与循环渲染
  1. // 列表渲染 - 使用 ForEach 遍历数据
  2. @Component
  3. struct ListDemo {
  4.   @State fruits: string[] = ['苹果', '香蕉', '橙子', '葡萄'];
  5.   build() {
  6.     Column({ space: 10 }) {
  7.       Text('水果列表')
  8.         .fontSize(24)
  9.         .fontWeight(FontWeight.Medium)
  10.       List({ space: 10 }) {
  11.         ForEach(this.fruits, (fruit: string, index: number) => {
  12.           ListItem() {
  13.             Row() {
  14.               Text(`${index + 1}.`)
  15.                 .fontSize(16)
  16.                 .fontColor('#666666')
  17.                 .width(40)
  18.               Text(fruit)
  19.                 .fontSize(18)
  20.                 .fontWeight(FontWeight.Medium)
  21.             }
  22.             .width('100%')
  23.             .padding(12)
  24.             .backgroundColor('#F5F5F5')
  25.             .borderRadius(8)
  26.           }
  27.         })
  28.       }
  29.       .width('90%')
  30.       .height('60%')
  31.     }
  32.     .width('100%')
  33.     .height('100%')
  34.     .padding(20)
  35.   }
  36. }
复制代码

四、页面路由与导航
HarmonyOS NEXT 推荐使用 Navigation 组件实现页面导航。通过 NavPathStack 管理页面栈,使用 pushPathByName 跳转并传递参数,pop 返回上一页。需要在 module.json5 中配置路由映射,并在 resources/base/profile/router_map.json 中定义路由表。详细代码示例如下:
  1. // src/main/ets/pages/MainPage.ets
  2. @Entry
  3. @Component
  4. struct MainPage {
  5.   @Provide('pageStack') pageStack: NavPathStack = new NavPathStack();
  6.   build() {
  7.     Navigation(this.pageStack) {
  8.       Column({ space: 20 }) {
  9.         Text('主页面')
  10.           .fontSize(32)
  11.           .fontWeight(FontWeight.Bold)
  12.         Button('跳转到详情页')
  13.           .onClick(() => {
  14.             this.pageStack.pushPathByName('DetailPage', {
  15.               'title': '详情标题',
  16.               'id': 1001
  17.             });
  18.           })
  19.       }
  20.       .width('100%')
  21.       .height('100%')
  22.       .justifyContent(FlexAlign.Center)
  23.     }
  24.     .title('应用首页')
  25.     .navDestination(this.routerBuilder)
  26.   }
  27.   @Builder
  28.   routerBuilder(name: string, param: Object) {
  29.     if (name === 'DetailPage') {
  30.       DetailPage({ param: param as Record<string, number> });
  31.     }
  32.   }
  33. }
  34. @Component
  35. struct DetailPage {
  36.   @Consume('pageStack') pageStack: NavPathStack;
  37.   @Param param: Record<string, number> = {};
  38.   build() {
  39.     NavDestination() {
  40.       Column({ space: 20 }) {
  41.         Text(`接收到的ID: ${this.param['id']}`)
  42.           .fontSize(24)
  43.         Button('返回')
  44.           .onClick(() => {
  45.             this.pageStack.pop();
  46.           })
  47.       }
  48.       .width('100%')
  49.       .height('100%')
  50.       .justifyContent(FlexAlign.Center)
  51.     }
  52.     .title('详情页')
  53.   }
  54. }
复制代码
路由配置文件示例:
  1. {
  2.   "srcEntry": "./ets/entryability/EntryAbility.ets",
  3.   "routerMap": "$profile:router_map"
  4. }
  5. // resources/base/profile/router_map.json
  6. {
  7.   "routerMap": [
  8.     {
  9.       "name": "MainPage",
  10.       "pageSourceFile": "./ets/pages/MainPage.ets",
  11.       "components": {
  12.         "DetailPage": "./ets/pages/DetailPage.ets"
  13.       }
  14.     }
  15.   ]
  16. }
复制代码

五、数据管理快速方案
ArkUI 的状态管理通过装饰器实现。核心装饰器包括:@State(组件私有状态)、@Prop(单向接收父组件数据)、@Link(双向绑定)、@Provide/@Consume(跨级状态共享)。当状态变化时,框架自动触发渲染更新。以下是一个完整的状态管理示例:
  1. @Entry
  2. @Component
  3. struct StateDemo {
  4.   @State count: number = 0;
  5.   @State inputText: string = '';
  6.   @Provide('appTheme') theme: string = 'light';
  7.   build() {
  8.     Column({ space: 20 }) {
  9.       Text(`计数: ${this.count}`).fontSize(28)
  10.       Row({ space: 10 }) {
  11.         Button('+1').onClick(() => this.count++)
  12.         Button('-1').onClick(() => this.count--)
  13.         Button('重置').onClick(() => this.count = 0)
  14.       }
  15.       TextInput({ placeholder: '请输入文本' })
  16.         .width('80%')
  17.         .height(50)
  18.         .onChange((value: string) => { this.inputText = value; })
  19.       Text(`输入的内容: ${this.inputText}`).fontSize(18).fontColor('#666666')
  20.       ChildComponent()
  21.     }
  22.     .width('100%')
  23.     .height('100%')
  24.     .padding(20)
  25.   }
  26. }
  27. @Component
  28. struct ChildComponent {
  29.   @Prop message: string = '来自父组件的消息';
  30.   @Consume('appTheme') theme: string;
  31.   build() {
  32.     Column({ space: 10 }) {
  33.       Text(this.message).fontSize(16)
  34.       Text(`当前主题: ${this.theme}`).fontSize(14).fontColor('#888888')
  35.     }
  36.     .padding(15)
  37.     .backgroundColor('#F0F0F0')
  38.     .borderRadius(10)
  39.   }
  40. }
复制代码

六、快速开发实战示例 - Todo App
下面是一个完整的待办事项应用,涵盖列表渲染、状态管理、增删操作:
  1. @Observed
  2. class TodoItem {
  3.   id: number;
  4.   title: string;
  5.   completed: boolean;
  6.   constructor(id: number, title: string) {
  7.     this.id = id;
  8.     this.title = title;
  9.     this.completed = false;
  10.   }
  11. }
  12. @Entry
  13. @Component
  14. struct TodoApp {
  15.   @State todoList: TodoItem[] = [];
  16.   @State newTodoTitle: string = '';
  17.   addTodo() {
  18.     if (this.newTodoTitle.trim() === '') return;
  19.     const newItem = new TodoItem(Date.now(), this.newTodoTitle.trim());
  20.     this.todoList.push(newItem);
  21.     this.newTodoTitle = '';
  22.   }
  23.   toggleTodo(item: TodoItem) {
  24.     item.completed = !item.completed;
  25.     this.todoList = [...this.todoList];
  26.   }
  27.   deleteTodo(id: number) {
  28.     const index = this.todoList.findIndex(item => item.id === id);
  29.     if (index !== -1) {
  30.       this.todoList.splice(index, 1);
  31.       this.todoList = [...this.todoList];
  32.     }
  33.   }
  34.   build() {
  35.     Column({ space: 16 }) {
  36.       Text('我的待办').fontSize(28).fontWeight(FontWeight.Bold).width('100%').textAlign(TextAlign.Start)
  37.       Row({ space: 10 }) {
  38.         TextInput({ placeholder: '添加新待办...', text: this.newTodoTitle })
  39.           .layoutWeight(1).height(48)
  40.           .onChange((value: string) => { this.newTodoTitle = value; })
  41.         Button('添加').height(48).fontSize(16).onClick(() => this.addTodo())
  42.       }.width('100%')
  43.       List({ space: 12 }) {
  44.         ForEach(this.todoList, (item: TodoItem) => {
  45.           ListItem() {
  46.             Row({ space: 12 }) {
  47.               Checkbox().select(item.completed).onChange((checked: boolean) => { this.toggleTodo(item); })
  48.               Text(item.title)
  49.                 .fontSize(18)
  50.                 .decoration({ type: item.completed ? TextDecorationType.LineThrough : TextDecorationType.None })
  51.                 .fontColor(item.completed ? '#999999' : '#333333')
  52.                 .layoutWeight(1)
  53.               Button('删除').fontSize(14).fontColor('#FF4444').backgroundColor('transparent').onClick(() => this.deleteTodo(item.id))
  54.             }.width('100%').padding(16).backgroundColor('#FFFFFF').borderRadius(12).shadow({ radius: 4, color: '#10000000', offsetX: 2, offsetY: 2 })
  55.           }
  56.         })
  57.       }.width('100%').layoutWeight(1)
  58.       Text(`共 ${this.todoList.length} 项,已完成 ${this.todoList.filter(i => i.completed).length} 项`)
  59.         .fontSize(14).fontColor('#666666').width('100%').textAlign(TextAlign.Center)
  60.     }.width('100%').height('100%').padding(20).backgroundColor('#F5F5F5')
  61.   }
  62. }
复制代码

七、开发效率提升技巧
- 热重载(Hot Reload):DevEco Studio 支持保存即生效的热重载功能,修改 .ets 文件并保存后,模拟器/设备会即时刷新,状态数据默认保留,极大加速 UI 调试循环。
- 预览器:右键点击 .ets 文件 → Preview 打开预览面板,支持多设备预览(手机、平板、智慧屏),实时查看不同屏幕尺寸下的布局效果。
- 代码片段(Code Snippets):DevEco Studio 内置常用代码模板,可快速生成组件模板。
- 快速调试技巧:使用 hilog 进行日志输出,带标签便于过滤;也可在预览器中使用 console.info 调试。
  1. import hilog from '@ohos.hilog';
  2. hilog.info(0xFF00, 'MyApp', 'User logged in: %{public}s', userName);
  3. hilog.error(0xFF00, 'MyApp', 'Network error: %{public}d', errorCode);
  4. console.info('State changed:', JSON.stringify(this.state));
复制代码

总结
鸿蒙应用开发的核心在于掌握 ArkTS 声明式语法 + 状态驱动渲染 + Navigation 路由系统。环境搭建仅需 DevEco Studio + Full SDK;项目结构清晰,UI 开发使用 Column/Row 布局 + 基础组件 + ForEach 列表渲染;状态管理按需选用 @State/@Prop/@Link/@Provide/@Consume;页面导航通过 Navigation + NavPathStack 实现;同时善用热重载、预览器和代码片段可大幅提升开发效率。
回复

使用道具 举报

发表于 2 小时前 | 显示全部楼层

Re: HarmonyOS NEXT快速开发实战:从环境搭建到Todo App

感谢楼主的详细教程!从环境搭建到 Todo App 的完整流程很清晰,特别是 ArkTS 声明式 UI 和 ForEach 列表渲染的示例,对刚接触 HarmonyOS NEXT 的开发者非常友好。请问在页面路由部分,如果使用 Navigation + NavPathStack,多个页面之间如何共享全局状态(比如用户登录信息)呢?另外,有没有推荐的 ArkUI 组件库或最佳实践,用于快速构建复杂界面?再次感谢分享!
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

指导单位

江苏省公安厅

江苏省通信管理局

浙江省台州刑侦支队

DEFCON GROUP 86025

Hacking Group 021A

旗下站点

态势感知中心

应急响应中心

红盟安全

联系我们

官方QQ群:112851260

官方邮箱:security#ihonker.org(#改成@)

官方核心成员

关注微信公众号

Archiver|手机版|小黑屋| ( 沪ICP备2021026908号 )

GMT+8, 2026-6-5 13:02 , Processed in 0.027082 second(s), 18 queries , Gzip On, Redis On.

Powered by ihonker.com

Copyright © 2015-现在.

  • 返回顶部