一、ArkTS 核心特点
- 声明式UI:通过组件化描述界面,自动响应数据变化。
- 类型系统:强类型(TypeScript 超集),支持静态类型检查。
- 状态管理 :使用
@State
、@Prop
、@Link
等装饰器管理组件状态。 - 组件化开发 :内置丰富的 UI 组件(如
Text
、Button
、Column
),支持自定义组件。
二、基础语法结构
1. 变量与类型
typescript
// 变量声明(类型注解)
let name: string = "ArkTS";
let age: number = 1;
let isActive: boolean = true;
// 常量
const PI: number = 3.14;
// 数组与元组
let list: number[] = [1, 2, 3];
let tuple: [string, number] = ["Harmony", 4];
2. 函数
typescript
// 普通函数
function greet(name: string): string {
return `Hello, ${name}!`;
}
// 箭头函数
const add = (a: number, b: number): number => a + b;
// 可选参数与默认值
function sayHello(name: string = "User", age?: number): void {
console.log(`Hello ${name}, age: ${age || "unknown"}`);
}
3. 类与继承
typescript
class Animal {
name: string;
constructor(name: string) {
this.name = name;
}
move(distance: number = 0): void {
console.log(`${this.name} moved ${distance}m.`);
}
}
class Dog extends Animal {
bark(): void {
console.log("Woof! Woof!");
}
}
const dog = new Dog("Buddy");
dog.bark(); // 输出: Woof! Woof!
dog.move(10); // 输出: Buddy moved 10m.
三、ArkTS 特有语法
1. 组件与装饰器
typescript
// 自定义组件
@Component
struct MyComponent {
// 状态变量(组件内私有)
@State count: number = 0;
build() {
Column() {
Text(`Count: ${this.count}`)
.fontSize(20)
Button('Click Me')
.onClick(() => {
this.count++; // 自动触发UI更新
})
}
}
}
// 入口组件
@Entry
@Component
struct Index {
build() {
Column() {
MyComponent() // 使用自定义组件
}
}
}
2. 状态管理装饰器
装饰器 | 说明 |
---|---|
@State |
组件内部状态,变化触发UI更新 |
@Prop |
从父组件传递的单向绑定数据 |
@Link |
父子组件双向绑定数据 |
@StorageLink |
持久化状态(如本地存储) |
示例:
typescript
@Component
struct ChildComponent {
@Prop message: string; // 父组件传递,单向绑定
build() {
Text(this.message)
}
}
@Entry
@Component
struct ParentComponent {
@State parentMessage: string = "Hello from Parent";
build() {
Column() {
ChildComponent({ message: this.parentMessage })
Button("Update Message")
.onClick(() => {
this.parentMessage = "Updated!";
})
}
}
}
四、UI 布局与样式
1. 常用布局容器
- Column:垂直排列子组件
- Row:水平排列子组件
- Stack:层叠布局
- List:列表布局(支持懒加载)
示例:
typescript
Column() {
Text("Top").fontSize(20)
Row() {
Text("Left").width(100)
Text("Right").width(100)
}
Stack() {
Text("Background").backgroundColor(Color.Gray)
Text("Foreground").fontColor(Color.Red)
}
}
2. 样式设置
typescript
Text("Hello ArkTS")
.fontSize(24) // 字体大小
.fontColor(Color.Blue) // 颜色
.margin({ top: 10, bottom: 20 }) // 外边距
.padding(10) // 内边距
.backgroundColor(Color.White) // 背景色
五、事件处理
typescript
Button("Click Me")
.onClick(() => { // 点击事件
console.log("Button clicked!");
})
TextInput()
.onChange((value: string) => { // 输入变化事件
console.log(`Input: ${value}`);
})
// 自定义事件(通过回调)
@Component
struct CustomEventComponent {
onCustomEvent: () => void = () => {};
build() {
Button("Trigger Event")
.onClick(() => {
this.onCustomEvent();
})
}
}
六、生命周期
ArkTS 组件生命周期方法:
aboutToAppear()
: 组件即将显示时调用aboutToDisappear()
: 组件即将销毁时调用
示例:
typescript
@Component
struct LifecycleDemo {
aboutToAppear() {
console.log("Component will appear");
}
aboutToDisappear() {
console.log("Component will disappear");
}
build() {
Text("Lifecycle Demo")
}
}
七、资源访问
1. 本地资源引用
typescript
Image($r("app.media.icon")) // 引用 resources 目录下的图片
Text($r("app.string.hello")) // 引用字符串资源
2. 模块导入
typescript
// 导入其他ArkTS文件
import { MyUtils } from '../utils/MyUtils';
// 使用系统模块
import router from '@ohos.router';
八、注意事项
- 类型严格性 :ArkTS 强制类型检查,避免使用
any
。 - UI 更新限制 :只有被
@State
、@Prop
等装饰的变量变化才会触发 UI 更新。 - 异步操作 :使用
async/await
或 Promise 处理异步任务。 - 代码规范 :推荐使用
.ets
文件扩展名,遵循华为鸿蒙开发规范。
总结
ArkTS 通过声明式语法和状态管理简化了 HarmonyOS 应用开发,核心在于理解 组件化 、装饰器 和 响应式UI更新机制 。可以结合华为官方文档和 IDE(DevEco Studio)实际练习组件开发与布局调试。下载中心直达