HarmonyOS NEXT快速开发实战:从环境搭建到Todo App
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。项目创建向导会自动生成以下核心结构:
entry/
├── src/main/
│ ├── ets/
│ │ ├── entryability/# 应用入口
│ │ │ └── EntryAbility.ets
│ │ ├── pages/# 页面文件
│ │ │ └── Index.ets# 主页面
│ │ └── App.ets# 全局应用配置
│ ├── module.json5# 模块配置
│ └── resources/# 资源目录
其中 entryability 管理应用生命周期,pages 定义 UI 页面,App.ets 用于全局配置。
三、常用 UI 组件快速上手
ArkUI 提供丰富的声明式组件,以下是最常用的基础组件。
3.1 文本与按钮
// Index.ets - 基础组件使用示例
import hilog from '@ohos.hilog';
@Component
struct Index {
@State message: string = 'Hello HarmonyOS';
build() {
Column({ space: 20 }) {
Text(this.message)
.fontSize(32)
.fontWeight(FontWeight.Bold)
.fontColor('#1A1A1A')
Button('点击我')
.width(200)
.height(50)
.fontSize(18)
.backgroundColor('#007DFF')
.borderRadius(25)
.onClick(() => {
this.message = '欢迎来到鸿蒙世界!';
hilog.info(0, 'Demo', 'Button clicked');
})
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)
.alignItems(HorizontalAlign.Center)
}
}
3.2 列表与循环渲染
// 列表渲染 - 使用 ForEach 遍历数据
@Component
struct ListDemo {
@State fruits: string[] = ['苹果', '香蕉', '橙子', '葡萄'];
build() {
Column({ space: 10 }) {
Text('水果列表')
.fontSize(24)
.fontWeight(FontWeight.Medium)
List({ space: 10 }) {
ForEach(this.fruits, (fruit: string, index: number) => {
ListItem() {
Row() {
Text(`${index + 1}.`)
.fontSize(16)
.fontColor('#666666')
.width(40)
Text(fruit)
.fontSize(18)
.fontWeight(FontWeight.Medium)
}
.width('100%')
.padding(12)
.backgroundColor('#F5F5F5')
.borderRadius(8)
}
})
}
.width('90%')
.height('60%')
}
.width('100%')
.height('100%')
.padding(20)
}
}
四、页面路由与导航
HarmonyOS NEXT 推荐使用 Navigation 组件实现页面导航。通过 NavPathStack 管理页面栈,使用 pushPathByName 跳转并传递参数,pop 返回上一页。需要在 module.json5 中配置路由映射,并在 resources/base/profile/router_map.json 中定义路由表。详细代码示例如下:
// src/main/ets/pages/MainPage.ets
@Entry
@Component
struct MainPage {
@Provide('pageStack') pageStack: NavPathStack = new NavPathStack();
build() {
Navigation(this.pageStack) {
Column({ space: 20 }) {
Text('主页面')
.fontSize(32)
.fontWeight(FontWeight.Bold)
Button('跳转到详情页')
.onClick(() => {
this.pageStack.pushPathByName('DetailPage', {
'title': '详情标题',
'id': 1001
});
})
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)
}
.title('应用首页')
.navDestination(this.routerBuilder)
}
@Builder
routerBuilder(name: string, param: Object) {
if (name === 'DetailPage') {
DetailPage({ param: param as Record<string, number> });
}
}
}
@Component
struct DetailPage {
@Consume('pageStack') pageStack: NavPathStack;
@Param param: Record<string, number> = {};
build() {
NavDestination() {
Column({ space: 20 }) {
Text(`接收到的ID: ${this.param['id']}`)
.fontSize(24)
Button('返回')
.onClick(() => {
this.pageStack.pop();
})
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)
}
.title('详情页')
}
}
路由配置文件示例:
{
"srcEntry": "./ets/entryability/EntryAbility.ets",
"routerMap": "$profile:router_map"
}
// resources/base/profile/router_map.json
{
"routerMap": [
{
"name": "MainPage",
"pageSourceFile": "./ets/pages/MainPage.ets",
"components": {
"DetailPage": "./ets/pages/DetailPage.ets"
}
}
]
}
五、数据管理快速方案
ArkUI 的状态管理通过装饰器实现。核心装饰器包括:@State(组件私有状态)、@Prop(单向接收父组件数据)、@Link(双向绑定)、@Provide/@Consume(跨级状态共享)。当状态变化时,框架自动触发渲染更新。以下是一个完整的状态管理示例:
@Entry
@Component
struct StateDemo {
@State count: number = 0;
@State inputText: string = '';
@Provide('appTheme') theme: string = 'light';
build() {
Column({ space: 20 }) {
Text(`计数: ${this.count}`).fontSize(28)
Row({ space: 10 }) {
Button('+1').onClick(() => this.count++)
Button('-1').onClick(() => this.count--)
Button('重置').onClick(() => this.count = 0)
}
TextInput({ placeholder: '请输入文本' })
.width('80%')
.height(50)
.onChange((value: string) => { this.inputText = value; })
Text(`输入的内容: ${this.inputText}`).fontSize(18).fontColor('#666666')
ChildComponent()
}
.width('100%')
.height('100%')
.padding(20)
}
}
@Component
struct ChildComponent {
@Prop message: string = '来自父组件的消息';
@Consume('appTheme') theme: string;
build() {
Column({ space: 10 }) {
Text(this.message).fontSize(16)
Text(`当前主题: ${this.theme}`).fontSize(14).fontColor('#888888')
}
.padding(15)
.backgroundColor('#F0F0F0')
.borderRadius(10)
}
}
六、快速开发实战示例 - Todo App
下面是一个完整的待办事项应用,涵盖列表渲染、状态管理、增删操作:
@Observed
class TodoItem {
id: number;
title: string;
completed: boolean;
constructor(id: number, title: string) {
this.id = id;
this.title = title;
this.completed = false;
}
}
@Entry
@Component
struct TodoApp {
@State todoList: TodoItem[] = [];
@State newTodoTitle: string = '';
addTodo() {
if (this.newTodoTitle.trim() === '') return;
const newItem = new TodoItem(Date.now(), this.newTodoTitle.trim());
this.todoList.push(newItem);
this.newTodoTitle = '';
}
toggleTodo(item: TodoItem) {
item.completed = !item.completed;
this.todoList = [...this.todoList];
}
deleteTodo(id: number) {
const index = this.todoList.findIndex(item => item.id === id);
if (index !== -1) {
this.todoList.splice(index, 1);
this.todoList = [...this.todoList];
}
}
build() {
Column({ space: 16 }) {
Text('我的待办').fontSize(28).fontWeight(FontWeight.Bold).width('100%').textAlign(TextAlign.Start)
Row({ space: 10 }) {
TextInput({ placeholder: '添加新待办...', text: this.newTodoTitle })
.layoutWeight(1).height(48)
.onChange((value: string) => { this.newTodoTitle = value; })
Button('添加').height(48).fontSize(16).onClick(() => this.addTodo())
}.width('100%')
List({ space: 12 }) {
ForEach(this.todoList, (item: TodoItem) => {
ListItem() {
Row({ space: 12 }) {
Checkbox().select(item.completed).onChange((checked: boolean) => { this.toggleTodo(item); })
Text(item.title)
.fontSize(18)
.decoration({ type: item.completed ? TextDecorationType.LineThrough : TextDecorationType.None })
.fontColor(item.completed ? '#999999' : '#333333')
.layoutWeight(1)
Button('删除').fontSize(14).fontColor('#FF4444').backgroundColor('transparent').onClick(() => this.deleteTodo(item.id))
}.width('100%').padding(16).backgroundColor('#FFFFFF').borderRadius(12).shadow({ radius: 4, color: '#10000000', offsetX: 2, offsetY: 2 })
}
})
}.width('100%').layoutWeight(1)
Text(`共 ${this.todoList.length} 项,已完成 ${this.todoList.filter(i => i.completed).length} 项`)
.fontSize(14).fontColor('#666666').width('100%').textAlign(TextAlign.Center)
}.width('100%').height('100%').padding(20).backgroundColor('#F5F5F5')
}
}
七、开发效率提升技巧
- 热重载(Hot Reload):DevEco Studio 支持保存即生效的热重载功能,修改 .ets 文件并保存后,模拟器/设备会即时刷新,状态数据默认保留,极大加速 UI 调试循环。
- 预览器:右键点击 .ets 文件 → Preview 打开预览面板,支持多设备预览(手机、平板、智慧屏),实时查看不同屏幕尺寸下的布局效果。
- 代码片段(Code Snippets):DevEco Studio 内置常用代码模板,可快速生成组件模板。
- 快速调试技巧:使用 hilog 进行日志输出,带标签便于过滤;也可在预览器中使用 console.info 调试。
import hilog from '@ohos.hilog';
hilog.info(0xFF00, 'MyApp', 'User logged in: %{public}s', userName);
hilog.error(0xFF00, 'MyApp', 'Network error: %{public}d', errorCode);
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 实现;同时善用热重载、预览器和代码片段可大幅提升开发效率。
Re: HarmonyOS NEXT快速开发实战:从环境搭建到Todo App
感谢楼主的详细教程!从环境搭建到 Todo App 的完整流程很清晰,特别是 ArkTS 声明式 UI 和 ForEach 列表渲染的示例,对刚接触 HarmonyOS NEXT 的开发者非常友好。请问在页面路由部分,如果使用 Navigation + NavPathStack,多个页面之间如何共享全局状态(比如用户登录信息)呢?另外,有没有推荐的 ArkUI 组件库或最佳实践,用于快速构建复杂界面?再次感谢分享!Re: HarmonyOS NEXT快速开发实战:从环境搭建到Todo App
感谢楼主的详细教程!环境搭建和项目结构讲得很清晰,ArkTS 的声明式写法看起来确实比传统 MVC 更直观,特别是 ForEach 循环渲染和 Navigation 路由那两部分,代码可读性很强。期待后续 Todo App 的完整实现,准备照着试试手。Re: HarmonyOS NEXT快速开发实战:从环境搭建到Todo App
感谢楼主分享的实战教程,从环境搭建到基础组件的用法都讲得很清晰,对刚接触HarmonyOS NEXT的开发者来说非常实用。特别是ForEach循环渲染列表的示例,代码结构很直观。想请问一下Todo App的完整实现是否会在后续楼层更新?另外,Navigation组件的路由映射除了配置router_map.json,是否还有其他方式(比如直接在代码里注册)?期待后续内容!
页:
[1]