HarmonyOS开发基础 -- ArkTS语法与类库系统性详解,一文搞懂全貌

2025-05-21 09:49:31
119次阅读
0个评论

本文系统梳理了鸿蒙(HarmonyOS)ArkTS语言的语法基础、常用类库及其生态特色,让初学者可以一文搞懂全貌,从全局把握,认清ArktS是什么,适合开发者快速了解和上手ArkTS开发。

作者 csdn猫哥,blog.csdn.net/yyz_1987。如需转载,请注明出处。

1. ArkTS简介

ArkTS(Ark TypeScript)是基于TypeScript的增强型编程语言,专为OpenHarmony(鸿蒙)ArkUI声明式开发设计。ArkTS兼容TypeScript大部分语法,并针对鸿蒙生态做了扩展,支持声明式UI、响应式状态管理、丰富的装饰器和组件开发能力。通过ArkTS,开发者可以更高效地构建跨端、分布式和响应式的应用程序。


2. ArkTS语言基础

2.1 变量与类型

  • 支持TypeScript的类型系统,包括number、string、boolean、Array、Tuple、Enum、Union、Literal等。
  • 支持类型推断、类型别名、接口、泛型等。

示例:

let count: number = 10;
let name: string = 'ArkTS';
let arr: number[] = [1, 2, 3];
interface User { id: number; name: string; }
let user: User = { id: 1, name: 'Tom' };

2.2 函数与类

  • 支持函数声明、箭头函数、可选参数、默认参数、rest参数。
  • 支持class、继承、访问修饰符(public、private、protected)、静态成员、getter/setter等。

示例:

function add(a: number, b: number = 1): number { return a + b; }

class Animal {
  constructor(public name: string) {}
  speak() { console.log(this.name); }
}

class Dog extends Animal {
  bark() { console.log('Woof!'); }
}

2.3 特有语法

  • 支持struct结构体(声明式UI组件核心)、装饰器(@State、@Local等)、ForEach、Column、Row等UI语法糖。

示例:

@Component
struct Counter {
  @State count: number = 0;
  build() {
    Column() {
      Text(`Count: ${this.count}`).fontSize(24)
      Button('Add').onClick(() => { this.count++; })
    }
  }
}

3. ArkTS声明式UI开发

3.1 组件结构

  • 组件以struct声明,build方法返回UI结构。
  • 支持@Entry(入口)、@Component/@ComponentV2(组件)、@State/@Local(状态)等装饰器。

示例:

@Entry
@Component
struct App {
  build() {
    Column() {
      Text('Hello ArkTS').fontSize(32).fontWeight(FontWeight.Bold)
    }
  }
}

3.2 常用UI组件

  • 提供丰富的UI组件,如Text、Button、Image、List、Grid、Column、Row、Stack等。
  • 支持属性链式调用和事件绑定。

示例:

Column() {
  Text('标题').fontSize(24).fontWeight(FontWeight.Bold)
  Button('点击').onClick(() => { console.log('按钮被点击'); })
}

3.3 响应式状态管理

  • 支持@State(组件内状态,自动刷新UI)、@Local(组件内部状态,V2专用)、@Prop(父子单向同步)、@Link(父子双向同步)、@ObservedV2(类深度观测,配合@Trace)、@Trace(类属性深度观测)等装饰器。
  • 状态变量变化自动驱动UI刷新。

示例:

@Component
struct Counter {
  @State count: number = 0;
  build() {
    Column() {
      Text(`Count: ${this.count}`).fontSize(24)
      Button('Add').onClick(() => { this.count++; })
    }
  }
}

4. ArkTS常用装饰器

装饰器 作用 适用版本
@State 组件内状态,自动刷新UI V1
@Local 组件内部状态,V2专用 V2
@Prop 父子单向同步 V1
@Link 父子双向同步 V1
@ObservedV2 类深度观测,配合@Trace V2
@Trace 类属性深度观测 V2
@Provider/@Consumer 跨组件层级双向同步 V2
@Event 组件事件输出 V2
@Monitor 深度监听状态变量变化 V2
@Watch 监听状态变量变化 V1

4.1 详细说明

@State

  • 仅能在@Component中使用。
  • 变量可本地初始化,也可由父组件初始化。
  • 变量变化会自动刷新绑定的UI。

@Local

  • 仅能在@ComponentV2中使用。
  • 表示组件内部状态,变量必须本地初始化,不能被外部初始化。
  • 变量变化会自动刷新绑定的UI。

@Prop

  • 仅能在@Component中使用。
  • 父组件向子组件单向传递数据。
  • 子组件不能修改@Prop变量,只能读取。

@Link

  • 仅能在@Component中使用。
  • 父组件与子组件双向同步数据。
  • 支持复杂的双向数据绑定。

@ObservedV2

  • 用于装饰class,使其支持深度观测。
  • 配合@Trace装饰器使用,可以观测嵌套对象属性的变化。

@Trace

  • 用于装饰类属性,使其支持深度观测。
  • 配合@ObservedV2装饰器使用,可以观测嵌套对象属性的变化。

@Provider/@Consumer

  • 仅能在@ComponentV2中使用。
  • @Provider为数据提供方,@Consumer为数据消费方。
  • 通过aliasName(或属性名)建立绑定,实现跨组件层级的双向同步。

@Event

  • 仅能在@ComponentV2中使用。
  • 用于装饰回调方法,实现子组件向父组件传递事件。
  • 常与@Param配合使用,实现数据的双向同步。

@Monitor

  • 仅能在@ComponentV2或@ObservedV2装饰的类中使用。
  • 可监听多个属性的变化,支持深度监听。
  • 回调参数可获取变化前后的值。

@Watch

  • 仅能在@Component中使用。
  • 用于监听@State、@Prop、@Link等装饰的变量变化。
  • 回调函数名作为参数,便于处理状态变化。

5. ArkTS常用类库与API

5.1 UI类库

  • 提供丰富的UI组件,如Text、Button、Image、List、Grid、Column、Row、Stack等。
  • 支持动画、手势、布局、样式等。

示例:使用Grid组件

@Component
struct GridExample {
  build() {
    Grid() {
      ForEach(['Item 1', 'Item 2', 'Item 3'], (item) => {
        Text(item).fontSize(16).margin(8)
      })
    }
    .columnsTemplate('1fr 1fr 1fr')
    .rowsTemplate('1fr 1fr')
    .cellsGap({ columnsGap: 8, rowsGap: 8 })
  }
}

5.2 数据与存储

  • 支持本地存储(LocalStorage、AppStorage)、文件操作、数据库(DataAbility)。
  • 状态管理与数据同步能力强。

示例:使用AppStorage

import AppStorage from '@ohos.app.ability.data.appStorage';

@Component
struct StorageExample {
  @State count: number = AppStorage.Get<number>('count') ?? 0;

  build() {
    Column() {
      Text(`Count: ${this.count}`).fontSize(24)
      Button('Increment').onClick(() => {
        this.count++;
        AppStorage.Set<number>('count', this.count);
      })
    }
  }
}

5.3 网络与通信

  • 提供HttpRequest、WebSocket、蓝牙、NFC等API。
  • 支持多端设备间通信(分布式能力)。

示例:Http请求

import http from '@ohos.net.http';

@Component
struct HttpExample {
  @State data: string = '';

  build() {
    Column() {
      Text(`Data: ${this.data}`).fontSize(24)
      Button('Fetch Data').onClick(() => {
        let httpRequest = http.createHttp();
        httpRequest.request('https://api.example.com/data', {
          method: http.RequestMethod.GET,
          success: (result) => { this.data = result.result; },
          fail: (err) => { console.error(`Request failed: ${err.message}`); }
        });
      })
    }
  }
}

5.4 设备与系统能力

  • 提供传感器、定位、相机、音视频、系统设置等接口。

示例:使用传感器

import sensor from '@ohos.sensor';

@Component
struct SensorExample {
  @State acceleration: string = '';

  build() {
    Column() {
      Text(`Acceleration: ${this.acceleration}`).fontSize(24)
      Button('Start Sensor').onClick(() => {
        sensor.subscribe(sensor.SensorType.ACCELEROMETER, (data) => {
          this.acceleration = `X: ${data.x}, Y: ${data.y}, Z: ${data.z}`;
        });
      })
    }
  }
}

6. ArkTS与TypeScript的区别

  • 语法扩展:ArkTS在兼容TypeScript大部分语法的基础上,增加了struct、声明式UI、响应式装饰器等特性。
  • 生态集成:ArkTS专为鸿蒙生态设计,深度集成系统能力和分布式特性。
  • UI开发范式:ArkTS采用声明式UI开发,而TypeScript通常用于命令式编程。声明式UI开发更直观,组件生命周期和状态管理与TypeScript有本质区别。

示例:对比命令式和声明式编程

// 命令式编程(TypeScript)
class MyComponent {
  private count: number = 0;
  private displayElement: HTMLElement;

  constructor(displayElement: HTMLElement) {
    this.displayElement = displayElement;
  }

  increment() {
    this.count++;
    this.displayElement.innerHTML = `Count: ${this.count}`;
  }
}

// 声明式编程(ArkTS)
@Component
struct MyArkComponent {
  @State count: number = 0;

  build() {
    Column() {
      Text(`Count: ${this.count}`).fontSize(24)
      Button('Increment').onClick(() => { this.count++; })
    }
  }
}

7. 鸿蒙生态特色

  • 跨端统一开发:一套代码多端运行(手机、平板、穿戴、车机等)。
  • 分布式能力:支持设备间无缝协同,实现多设备之间的数据同步和功能协作。
  • 丰富的系统API和硬件能力开放:提供广泛的系统API和硬件接口,方便开发者调用。
  • 官方IDE DevEco Studio:支持ArkTS高效开发与调试,提供智能代码补全、调试器、性能分析等工具。

示例:使用分布式能力

import distributedData from '@ohos.data.distributedData';

@Component
struct DistributedExample {
  @State sharedData: string = '';

  build() {
    Column() {
      Text(`Shared Data: ${this.sharedData}`).fontSize(24)
      Button('Set Data').onClick(() => {
        distributedData.set('sharedKey', 'Hello from this device');
      })
      Button('Get Data').onClick(() => {
        distributedData.get('sharedKey').then((data) => {
          this.sharedData = data;
        });
      })
    }
  }
}

8. 参考资料


通过以上内容,开发者可以全面了解ArkTS的语法基础、常用类库及其生态特色,快速上手进行ArkTS开发。希望本文对开发者有所帮助。


结语

鸿蒙系统的ArkTS语言提供了强大的工具和丰富的功能,使得开发者能够更高效地构建跨端、分布式和响应式的应用程序。本文详细介绍了ArkTS的语法基础、常用装饰器、类库与API以及鸿蒙生态特色,帮助开发者更好地理解和应用这些概念。建议开发者参考官方文档和社区资源,进一步深入学习和实践。


希望这篇完善后的文档能够更好地帮助开发者快速了解和上手ArkTS开发。

作者

csdn猫哥,blog.csdn.net/yyz_1987。如需转载,请注明出处。

收藏00

登录 后评论。没有帐号? 注册 一个。