鸿蒙HarmonyOS Next - ArkTS基础语法学习笔记

华为开发者HarmonyOS NEXT在线课程直达


一、ArkTS 核心特点

  1. 声明式UI:通过组件化描述界面,自动响应数据变化。
  2. 类型系统:强类型(TypeScript 超集),支持静态类型检查。
  3. 状态管理 :使用 @State@Prop@Link 等装饰器管理组件状态。
  4. 组件化开发 :内置丰富的 UI 组件(如 TextButtonColumn),支持自定义组件。

二、基础语法结构

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';

八、注意事项

  1. 类型严格性 :ArkTS 强制类型检查,避免使用 any
  2. UI 更新限制 :只有被 @State@Prop 等装饰的变量变化才会触发 UI 更新。
  3. 异步操作 :使用 async/await 或 Promise 处理异步任务。
  4. 代码规范 :推荐使用 .ets 文件扩展名,遵循华为鸿蒙开发规范。

总结

ArkTS 通过声明式语法和状态管理简化了 HarmonyOS 应用开发,核心在于理解 组件化装饰器响应式UI更新机制 。可以结合华为官方文档和 IDE(DevEco Studio)实际练习组件开发与布局调试。下载中心直达

相关推荐
尾善爱看海9 小时前
不常用的浏览器 API —— Web Speech
前端
美酒没故事°10 小时前
vue3拖拽+粘贴的综合上传器
前端·javascript·typescript
奔跑的露西ly10 小时前
【HarmonyOS NEXT】解决:软键盘弹起导致页面整体上移、标题栏丢失的问题
华为·harmonyos·鸿蒙·键盘
jingling55511 小时前
css进阶 | 实现罐子中的水流搅拌效果
前端·css
鸣弦artha12 小时前
Flutter框架跨平台鸿蒙开发——Widget体系概览
flutter·华为·harmonyos
南村群童欺我老无力.12 小时前
Flutter 框架跨平台鸿蒙开发 - 打造安全可靠的密码生成器,支持强度检测与历史记录
flutter·华为·typescript·harmonyos
悟能不能悟12 小时前
前端上载文件时,上载多个文件,但是一个一个调用接口,怎么实现
前端
可问春风_ren13 小时前
前端文件上传详细解析
前端·ecmascript·reactjs·js
鸣弦artha13 小时前
Flutter 框架跨平台鸿蒙开发——Flutter引擎层架构概览
flutter·架构·harmonyos
羊小猪~~13 小时前
【QT】--文件操作
前端·数据库·c++·后端·qt·qt6.3