【鸿蒙App】ArkTD/ArkUI核心语法和开发要点

ArkTS 是华为为鸿蒙OS(HarmonyOS)设计的主力开发语言,基于 TypeScript(TS)扩展,结合了声明式UI框架 ArkUI,用于高效开发原生鸿蒙应用。以下是 ArkTS/ArkUI 的核心语法和开发要点:


1. ArkTS 基础语法

ArkTS 是 TypeScript 的超集,继承了 TS 的静态类型、类、模块等特性,并增加了鸿蒙特有的装饰器和API。

1.1 基本类型与变量

// 1. 变量声明(支持类型推断)
let name: string = "HarmonyOS";  // 显式类型
let version = 4.0;              // 自动推断为 number

// 2. 常量
const isNEXT: boolean = true;

// 3. 联合类型
let device: "phone" | "tablet" | "tv" = "phone";

1.2 函数

// 普通函数
function greet(message: string): void {
  console.log(message);
}

// 箭头函数
const sum = (a: number, b: number): number => a + b;

1.3 类与继承

class Device {
  name: string;

  constructor(name: string) {
    this.name = name;
  }

  boot(): void {
    console.log(`${this.name} is booting...`);
  }
}

class Phone extends Device {
  call(): void {
    console.log("Making a call...");
  }
}

2. ArkUI 声明式语法

ArkUI 采用声明式UI开发模式(类似 SwiftUI/Flutter),通过装饰器(如@Entry@Component)定义组件。

2.1 基本组件

@Entry
@Component
struct MyComponent {
  // 状态变量(触发UI更新)
  @State count: number = 0;

  build() {
    // 必须返回一个根组件(如 Column, Row, Stack)
    Column() {
      Text(`Count: ${this.count}`)
        .fontSize(20)
        .fontColor("#FF0000")

      Button("Click Me")
        .onClick(() => {
          this.count++; // 修改状态自动更新UI
        })
    }
    .width("100%")
    .height("100%")
  }
}
常用内置组件
组件说明示例
Text文本Text("Hello")
Button按钮Button("OK")
Image图片Image("res/icon.png")
Column垂直布局Column() { ... }
Row水平布局Row() { ... }
Stack层叠布局Stack() { ... }

2.2 状态管理

1. @State

组件内部状态,变化时触发UI更新。

@State isActive: boolean = false;

Button(this.isActive ? "Active" : "Inactive")
  .onClick(() => {
    this.isActive = !this.isActive;
  })
2. @Prop

从父组件传递的可变状态。

@Component
struct ChildComponent {
  @Prop message: string; // 父组件传递的值
  // ...
}
3. @Link

双向绑定,父子组件共享状态。

@Component
struct ParentComponent {
  @State sharedValue: number = 0;

  build() {
    Column() {
      ChildComponent({ value: $sharedValue }) // 使用 $ 符号传递Link
    }
  }
}

@Component
struct ChildComponent {
  @Link value: number; // 修改会影响父组件
}

2.3 条件与循环渲染

条件渲染:if 语句
Column() {
  if (this.isActive) {
    Text("Active").fontSize(20)
  } else {
    Text("Inactive").fontColor("gray")
  }
}
循环渲染:ForEach
@State items: string[] = ["Apple", "Banana", "Orange"];

Column() {
  ForEach(this.items, (item: string) => {
    Text(item)
      .margin(5)
  })
}

3. 页面导航与生命周期

3.1 页面跳转(路由)

import router from '@ohos.router';

// 跳转到指定页面
router.pushUrl({
  url: "pages/DetailPage",
  params: { id: 123 } // 传递参数
});

// 接收参数
@State id: number = 0;

onPageShow() {
  const params = router.getParams();
  this.id = params?.id || 0;
}

3.2 生命周期

装饰器说明
onPageShow页面显示时触发
onPageHide页面隐藏时触发
onBackPress返回按钮事件
@Entry
@Component
struct HomePage {
  onPageShow() {
    console.log("Page shown");
  }
}

4. 样式与布局

4.1 内联样式

Text("Hello ArkUI")
  .fontSize(20)
  .fontColor("#FF0000")
  .margin({ top: 10, bottom: 10 })

4.2 外部样式(styles.ets

// 定义样式
export const titleStyle = {
  fontSize: 24,
  fontWeight: "bold",
  color: "#000000"
};

// 使用样式
import { titleStyle } from "../styles.ets";

Text("Title")
  .style(titleStyle)

5. 网络请求

使用鸿蒙的@ohos.net.http模块:

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

let request = http.createHttp();
request.request(
  "https://api.example.com/data",
  {
    method: "GET",
    header: { "Content-Type": "application/json" }
  },
  (err, data) => {
    if (!err) {
      console.log("Response:", data.result);
    }
  }
);

总结:ArkTS/ArkUI 核心特点

  1. 基于TypeScript:强类型、面向对象。
  2. 声明式UI:通过@Component和装饰器构建界面。
  3. 状态驱动@State@Prop@Link 管理状态。
  4. 跨设备能力:适配手机、平板、智慧屏等。

学习资源

掌握这些语法后,即可高效开发HarmonyOS NEXT应用!

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Botiway

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值