ArkTs语法介绍
ArkTs是HarmonyOS(鸿蒙操作系统)开发中使用的编程语言,它基于TypeScript进行了扩展,专为鸿蒙应用设计,支持声明式UI、状态管理等特性。
1. 基础语法元素
ArkTs继承了TypeScript的核心语法,包括:
- 变量声明:使用
let
或const
,类型可显式或隐式推导。let name: string = 'HarmonyOS' // 显式类型 name = 'Hello' // 修改值 const version = 4.0 // 隐式推导为number
- 函数定义:支持传统函数或箭头函数。
function greet(msg: string): void { console.log(msg) } const add = (a: number, b: number): number => a + b; // 箭头函数
- 控制结构:如
if
、for
、switch
等,语法与JavaScript/TypeScript一致。for (let i = 0; i < 10; i++){ if(i%2 ===0){ console.log('',i) } }
2. 面向对象编程
ArkTs支持类和结构体(struct),用于组件化开发:
- 类(Class):定义属性和方法。
class Device { private model: string; constructor(model: string) { this.model = model } display(): void { console.log(`Device: ${this.model}`) } }
- 结构体(Struct):鸿蒙特有,用于UI组件,结合装饰器。
@Component struct MyButton { // 定义组件属性(支持外部传入) @Prop label: string = 'Click Me' // 必须实现build()方法,用于描述UI结构 build() { Column() { Button(this.label) .onClick(()=>{ this.label = 'Clicked' }) .backgroundColor('#007DFF') .padding({ left: 20, right: 20, top: 10, bottom: 10 }) } } }
3. 鸿蒙特有特性
ArkTs的核心扩展在于声明式UI和状态管理:
-
装饰器(Decorators):用于标记组件、状态或入口。
@Entry
: 标记应用入口组件。@Component
: 定义可复用的UI组件。@State
: 管理组件内部状态,状态变化时UI自动更新。@Prop
和@Link
: 用于父子组件数据传递。
示例:
@Entry @Component struct HomePage { @State count: number = 0; // 状态变量 build() { Column() { Text(this.count) .fontSize(20) Button('按钮') .onClick(() => { this.count++ // 状态更新触发UI刷新 }) } } }
-
声明式UI:使用链式调用构建UI,如
Column()
、Row()
、Text()
等。@Component struct MyComponent { build() { Column() { // 垂直布局 Text('Hello ArkTS') .fontSize(30) .fontColor(Color.Blue) Image($r('app.media.app')) .width(100) .height(100) } .padding(10) } }
4. 类型系统和高级特性
- 类型注解:支持TypeScript的类型系统,包括接口、泛型等。
interface User { id: number; name: string; } function getUser<T>(id:T): User { // 泛型示例 return { id: 10, name: 'John Doe' }; }
- 异步编程:使用
async/await
处理异步操作。// 异步处理点击事件 private async onLoadData(): Promise<void> { this.isLoading = true try { // 使用 await 等待异步操作完成 const result = await this.fetchData() this.data = result } catch (error) { this.data = 'Error loading data' console.error('Failed to load data:', error) } finally { this.isLoading = false } }