快速上手
本章节将通过一个简单的示例,带你快速了解 HarmonyOS 应用开发的基本流程。
创建第一个应用
1. 创建项目
打开 DevEco Studio,创建一个新项目:
- 选择 File → New → Create Project
- 选择 Application → Empty Ability
- 填写项目信息:
- Project name: HelloHarmonyOS
- Bundle name: com.example.hello
- Save location: 选择项目保存路径
- 点击 Finish
2. 项目结构
创建完成后,你会看到以下目录结构:
HelloHarmonyOS/
├── entry/ # 主模块
│ └── src/
│ └── main/
│ ├── ets/ # ArkTS 代码
│ │ └── pages/
│ │ └── Index.ets
│ ├── resources/ # 资源文件
│ └── module.json5 # 模块配置
└── oh-package.json5 # 项目配置3. 编写第一个页面
打开 entry/src/main/ets/pages/Index.ets,你会看到默认的页面代码:
typescript
@Entry
@Component
struct Index {
@State message: string = 'Hello World'
build() {
Row() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
}
.width('100%')
}
.height('100%')
}
}让我们对其进行修改:
typescript
@Entry
@Component
struct Index {
@State message: string = 'Hello HarmonyOS'
@State count: number = 0
build() {
Column() {
// 标题
Text(this.message)
.fontSize(40)
.fontWeight(FontWeight.Bold)
.margin({ top: 50, bottom: 30 })
// 计数器显示
Text(`点击次数: ${this.count}`)
.fontSize(24)
.margin({ bottom: 20 })
// 按钮
Button('点击我')
.fontSize(20)
.width(200)
.height(50)
.onClick(() => {
this.count++
})
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)
}
}4. 运行应用
- 点击工具栏的 Run 按钮(▶️)
- 选择设备(模拟器或真机)
- 等待编译和安装
- 应用将自动启动
提示
首次运行需要编译和安装,可能需要几分钟时间。
代码解析
装饰器
typescript
@Entry // 标记为入口组件
@Component // 标记为自定义组件
@State // 声明状态变量HarmonyOS 使用装饰器来增强组件功能,这些装饰器提供了:
- @Entry: 标识页面入口
- @Component: 定义自定义组件
- @State: 定义响应式状态
UI 结构
typescript
build() {
Column() { // 列容器
Text('文本') // 文本组件
Button('按钮') // 按钮组件
}
}使用声明式语法描述 UI 结构,组件嵌套形成树状结构。
样式设置
typescript
Text('Hello')
.fontSize(40) // 字体大小
.fontWeight(FontWeight.Bold) // 字体粗细
.margin({ top: 50 }) // 外边距通过链式调用的方式设置组件样式。
事件处理
typescript
Button('点击')
.onClick(() => {
this.count++ // 更新状态
})使用 .onClick() 等方法绑定事件处理函数。
常用组件示例
图片显示
typescript
Image($r('app.media.icon'))
.width(100)
.height(100)
.borderRadius(10)文本输入
typescript
@State inputValue: string = ''
TextInput({ placeholder: '请输入内容' })
.width('80%')
.height(50)
.onChange((value: string) => {
this.inputValue = value
})列表渲染
typescript
@State items: string[] = ['项目1', '项目2', '项目3']
List() {
ForEach(this.items, (item: string) => {
ListItem() {
Text(item)
.fontSize(20)
.padding(10)
}
})
}
.width('100%')状态管理
@State 装饰器
@State 用于声明组件内部的状态变量,当状态改变时,UI 会自动更新。
typescript
@State count: number = 0 // 数字
@State message: string = '' // 字符串
@State isVisible: boolean = true // 布尔值
@State items: string[] = [] // 数组@Prop 装饰器
@Prop 用于父子组件间的单向数据传递。
typescript
@Component
struct ChildComponent {
@Prop count: number
build() {
Text(`父组件传来的值: ${this.count}`)
}
}下一步
恭喜你完成了第一个 HarmonyOS 应用!接下来可以:
注意
在实际开发中,建议遵循官方的开发规范和最佳实践。