ArkTS 常用 API 总结

📌 快速概览

ArkTS API 是鸿蒙应用开发的核心工具集,涵盖 UI 组件、系统能力、工具类等。

分类:UI 组件 API、系统能力 API、工具类 API、路由导航 API


🎯 API 分类体系

ArkTS API 体系
├─ UI 组件 API
│  ├─ 容器组件(Column, Row, Stack...)
│  ├─ 基础组件(Text, Button, Image...)
│  ├─ 列表组件(List, Grid, Swiper...)
│  └─ 表单组件(TextInput, Checkbox, Slider...)
│
├─ 系统能力 API
│  ├─ 网络请求(@ohos.net.http)
│  ├─ 数据存储(@ohos.data.preferences)
│  ├─ 文件管理(@ohos.file.fs)
│  └─ 设备能力(相机、定位、传感器...)
│
├─ 路由导航 API
│  ├─ 页面路由(@ohos.router)
│  └─ Navigation 导航组件
│
├─ 动画与手势 API
│  ├─ 属性动画(animation, transition)
│  └─ 手势识别(TapGesture, PanGesture...)
│
└─ 工具类 API
   ├─ 内置对象(JSON, Math, Date...)
   └─ 日志工具(console, hilog)

📖 UI 组件 API

1. 容器组件

Column - 垂直布局容器

Column({ space: 10 }) {  // space:子组件间距
  Text('第一项')
  Text('第二项')
}
.width('100%')
.alignItems(HorizontalAlign.Center)  // 水平对齐

Row - 水平布局容器

Row({ space: 10 }) {
  Text('左侧')
  Text('右侧')
}
.width('100%')
.justifyContent(FlexAlign.SpaceBetween)  // 主轴对齐

Stack - 堆叠容器

Stack({ alignContent: Alignment.TopStart }) {
  Image('bg.jpg')  // 背景层
  Text('覆盖文字')  // 覆盖层
}

Flex - 弹性布局容器

Flex({ direction: FlexDirection.Row, wrap: FlexWrap.Wrap }) {
  Text('项目1').flexGrow(1)
  Text('项目2').flexGrow(2)
}

2. 基础组件

Text - 文本显示

Text("Hello World")
  .fontSize(20)
  .fontColor(Color.Red)
  .fontWeight(FontWeight.Bold)
  .textAlign(TextAlign.Center);

Button - 按钮

Button("点击我")
  .type(ButtonType.Capsule) // 胶囊按钮
  .backgroundColor(Color.Blue)
  .onClick(() => {
    console.log("按钮被点击");
  });

Image - 图片

Image("path/to/image.png"); // 本地图片
Image("https://example.com/image.jpg") // 网络图片
  .width(200)
  .height(200)
  .objectFit(ImageFit.Cover); // 填充方式

Divider - 分割线

Divider().color(Color.Gray).strokeWidth(2).margin(10);

3. 列表组件

List - 列表容器

List({ space: 10 }) {
  ForEach(this.dataList, (item: Item) => {
    ListItem() {
      Text(item.title)
    }
  })
}
.width('100%')
.listDirection(Axis.Vertical)  // 滚动方向

Grid - 网格布局

Grid() {
  ForEach(this.items, (item: Item) => {
    GridItem() {
      Text(item.name)
    }
  })
}
.columnsTemplate('1fr 1fr 1fr')  // 3列
.rowsTemplate('1fr 1fr')         // 2行

Swiper - 轮播图

Swiper() {
  ForEach(this.images, (img: string) => {
    Image(img)
  })
}
.autoPlay(true)
.interval(3000)  // 自动切换间隔
.indicator(true)  // 显示指示器

Tabs - 标签页

Tabs() {
  TabContent() {
    Text('首页内容')
  }.tabBar('首页')

  TabContent() {
    Text('我的内容')
  }.tabBar('我的')
}

4. 表单组件

TextInput - 文本输入

TextInput({ placeholder: "请输入用户名" })
  .type(InputType.Normal) // 输入类型
  .maxLength(20)
  .onChange((value: string) => {
    this.username = value;
  });

Checkbox - 复选框

Checkbox({ name: "agree" })
  .select(false)
  .onChange((checked: boolean) => {
    this.isAgree = checked;
  });

Radio - 单选按钮

Radio({ value: "option1", group: "gender" })
  .checked(true)
  .onChange((checked: boolean) => {
    // 处理选中
  });

Slider - 滑块

Slider({ value: 50, min: 0, max: 100 }).onChange((value: number) => {
  this.volume = value;
});

Toggle - 开关

Toggle({ type: ToggleType.Switch, isOn: false }).onChange((isOn: boolean) => {
  this.isEnabled = isOn;
});

🌐 系统能力 API

1. 网络请求 - @ohos.net.http

发送 HTTP 请求

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

// 创建 HTTP 请求
let httpRequest = http.createHttp();

// GET 请求
httpRequest
  .request("https://api.example.com/data", {
    method: http.RequestMethod.GET,
    header: {
      "Content-Type": "application/json",
    },
  })
  .then((response: http.HttpResponse) => {
    console.log("响应数据:", response.result);
  })
  .catch((error: Error) => {
    console.error("请求失败:", error);
  });

// POST 请求
httpRequest
  .request("https://api.example.com/login", {
    method: http.RequestMethod.POST,
    header: {
      "Content-Type": "application/json",
    },
    extraData: JSON.stringify({
      username: "user",
      password: "pass",
    }),
  })
  .then((response) => {
    // 处理响应
  });

使用场景

  • 获取服务器数据
  • 提交表单
  • 上传/下载文件
  • RESTful API 调用

2. 数据存储 - @ohos.data.preferences

轻量级键值对存储

import preferences from "@ohos.data.preferences";

// 获取 Preferences 实例
preferences.getPreferences(this.context, "myStore").then((store) => {
  // 存储数据
  store.put("username", "张三");
  store.put("age", 25);
  store.flush(); // 持久化

  // 读取数据
  store.get("username", "默认值").then((value) => {
    console.log("用户名:", value);
  });

  // 删除数据
  store.delete("age");

  // 清空所有数据
  store.clear();
});

使用场景

  • 保存用户配置
  • 缓存少量数据
  • 存储登录状态
  • 保存应用设置

3. 文件管理 - @ohos.file.fs

文件读写操作

import fs from "@ohos.file.fs";

// 写入文件
let filePath = this.context.filesDir + "/test.txt";
let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
fs.writeSync(file.fd, "这是写入的内容");
fs.closeSync(file);

// 读取文件
let file2 = fs.openSync(filePath, fs.OpenMode.READ_ONLY);
let buffer = new ArrayBuffer(1024);
let readLen = fs.readSync(file2.fd, buffer);
let content = String.fromCharCode.apply(
  null,
  new Uint8Array(buffer.slice(0, readLen))
);
console.log("文件内容:", content);
fs.closeSync(file2);

// 删除文件
fs.unlinkSync(filePath);

使用场景

  • 保存用户文档
  • 缓存大文件
  • 日志记录
  • 离线数据存储

4. 弹窗提示 - @ohos.promptAction

Toast 提示

import promptAction from "@ohos.promptAction";

// Toast 提示
promptAction.showToast({
  message: "操作成功",
  duration: 2000, // 显示时长(毫秒)
});

对话框

// 警告对话框
promptAction
  .showDialog({
    title: "提示",
    message: "确定要删除吗?",
    buttons: [
      { text: "取消", color: "#000000" },
      { text: "确定", color: "#FF0000" },
    ],
  })
  .then((result) => {
    if (result.index === 1) {
      console.log("用户点击了确定");
    }
  });

使用场景

  • 操作成功/失败提示
  • 确认对话框
  • 选择对话框
  • 输入对话框

🧭 路由导航 API

router - 页面路由

导入路由模块

import router from "@ohos.router";

页面跳转

// 跳转到新页面
router.pushUrl({
  url: "pages/Detail",
  params: {
    id: 123,
    title: "详情页",
  },
});

// 替换当前页面
router.replaceUrl({
  url: "pages/Login",
});

// 返回上一页
router.back();

// 返回指定页面
router.back({
  url: "pages/Index",
});

获取路由参数

// 在目标页面接收参数
import router from '@ohos.router';

@Entry
@Component
struct DetailPage {
  @State id: number = 0
  @State title: string = ''

  aboutToAppear() {
    const params = router.getParams() as Record<string, Object>;
    this.id = params['id'] as number;
    this.title = params['title'] as string;
  }
}

使用场景

  • 页面跳转
  • 传递参数
  • 返回操作
  • 页面栈管理

🎨 动画 API

属性动画 - animation

基本动画

@State scale: number = 1

Button('放大')
  .scale({ x: this.scale, y: this.scale })
  .animation({
    duration: 500,      // 动画时长
    curve: Curve.EaseInOut,  // 动画曲线
    iterations: 1       // 播放次数
  })
  .onClick(() => {
    this.scale = 1.5
  })

转场动画 - transition

@State isShow: boolean = true

if (this.isShow) {
  Column() {
    Text('内容')
  }
  .transition({
    type: TransitionType.Insert,  // 入场动画
    opacity: 0,
    translate: { x: -100 }
  })
  .transition({
    type: TransitionType.Delete,  // 出场动画
    opacity: 0,
    translate: { x: 100 }
  })
}

显式动画 - animateTo

animateTo(
  {
    duration: 1000,
    curve: Curve.Linear,
  },
  () => {
    this.width = 200;
    this.height = 200;
  }
);

👆 手势 API

点击手势 - TapGesture

Text("点击我").gesture(
  TapGesture({ count: 1 }) // 单击
    .onAction(() => {
      console.log("被点击了");
    })
);

长按手势 - LongPressGesture

Text("长按我").gesture(
  LongPressGesture({ duration: 500 }).onAction(() => {
    console.log("长按触发");
  })
);

拖拽手势 - PanGesture

@State positionX: number = 0

Text('拖动我')
  .translate({ x: this.positionX })
  .gesture(
    PanGesture()
      .onActionUpdate((event: GestureEvent) => {
        this.positionX += event.offsetX
      })
  )

🛠️ 工具类 API

1. 数组常用方法

遍历方法

let arr = [1, 2, 3, 4, 5];

// forEach - 遍历数组
arr.forEach((item, index) => {
  console.log(`索引${index}: ${item}`);
});

// map - 映射新数组
let doubled = arr.map((item) => item * 2); // [2, 4, 6, 8, 10]

// filter - 过滤数组
let filtered = arr.filter((item) => item > 2); // [3, 4, 5]

// find - 查找元素
let found = arr.find((item) => item > 3); // 4

// some - 是否存在符合条件的元素
let hasEven = arr.some((item) => item % 2 === 0); // true

// every - 是否所有元素都符合条件
let allPositive = arr.every((item) => item > 0); // true

数组操作方法

let arr = [1, 2, 3];

// push - 末尾添加
arr.push(4); // [1, 2, 3, 4]

// pop - 末尾删除
arr.pop(); // [1, 2, 3]

// unshift - 开头添加
arr.unshift(0); // [0, 1, 2, 3]

// shift - 开头删除
arr.shift(); // [1, 2, 3]

// splice - 插入/删除
arr.splice(1, 1, 99); // [1, 99, 3] (从索引1删除1个,插入99)

// slice - 截取数组
let sliced = arr.slice(1, 3); // [99, 3]

// concat - 合并数组
let merged = arr.concat([4, 5]); // [1, 99, 3, 4, 5]

// join - 数组转字符串
let str = arr.join("-"); // "1-99-3"

// reverse - 反转数组
arr.reverse(); // [3, 99, 1]

// sort - 排序
arr.sort((a, b) => a - b); // [1, 3, 99]

数组归并方法

let numbers = [1, 2, 3, 4, 5];

// reduce - 累加
let sum = numbers.reduce((acc, cur) => acc + cur, 0); // 15

// reduce - 求最大值
let max = numbers.reduce((acc, cur) => (cur > acc ? cur : acc)); // 5

2. Math 数学运算

常用数学方法

// 绝对值
Math.abs(-5); // 5

// 向上取整
Math.ceil(4.3); // 5

// 向下取整
Math.floor(4.8); // 4

// 四舍五入
Math.round(4.5); // 5

// 最大值/最小值
Math.max(1, 5, 3); // 5
Math.min(1, 5, 3); // 1

// 幂运算
Math.pow(2, 3); // 8 (2的3次方)

// 平方根
Math.sqrt(16); // 4

// 随机数 [0, 1)
Math.random(); // 0.xxxxx

// 随机整数 [min, max]
function randomInt(min: number, max: number) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}
randomInt(1, 10); // 1-10之间的随机整数

常用数学常量

Math.PI; // 圆周率 3.141592653589793
Math.E; // 自然常数 2.718281828459045

3. Date 日期时间

创建日期对象

// 当前时间
let now = new Date();

// 指定时间
let date1 = new Date(2024, 0, 1); // 2024年1月1日
let date2 = new Date("2024-01-01");
let date3 = new Date(1704067200000); // 时间戳

获取日期时间

let date = new Date();

// 年月日
date.getFullYear(); // 2024
date.getMonth(); // 0-11 (0代表1月)
date.getDate(); // 1-31

// 时分秒
date.getHours(); // 0-23
date.getMinutes(); // 0-59
date.getSeconds(); // 0-59
date.getMilliseconds(); // 0-999

// 星期
date.getDay(); // 0-6 (0代表周日)

// 时间戳
date.getTime(); // 毫秒时间戳
Date.now(); // 当前时间戳(静态方法)

设置日期时间

let date = new Date();

date.setFullYear(2025);
date.setMonth(11); // 设置为12月
date.setDate(25);
date.setHours(12);
date.setMinutes(30);
date.setSeconds(0);

日期格式化

let date = new Date();

// 转字符串
date.toString(); // "Mon Oct 27 2024 10:30:00 GMT+0800"
date.toDateString(); // "Mon Oct 27 2024"
date.toTimeString(); // "10:30:00 GMT+0800"
date.toLocaleDateString(); // "2024/10/27"
date.toLocaleTimeString(); // "10:30:00"

// 自定义格式化
function formatDate(date: Date): string {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
}
formatDate(new Date()); // "2024-10-27"

日期计算

let date = new Date();

// 7天后
let future = new Date(date.getTime() + 7 * 24 * 60 * 60 * 1000);

// 计算两个日期相差天数
function daysBetween(date1: Date, date2: Date): number {
  const diff = Math.abs(date2.getTime() - date1.getTime());
  return Math.floor(diff / (1000 * 60 * 60 * 24));
}

4. String 字符串方法

常用字符串方法

let str = "Hello World";

// 长度
str.length; // 11

// 大小写转换
str.toUpperCase(); // "HELLO WORLD"
str.toLowerCase(); // "hello world"

// 查找
str.indexOf("o"); // 4
str.lastIndexOf("o"); // 7
str.includes("World"); // true
str.startsWith("Hello"); // true
str.endsWith("World"); // true

// 截取
str.substring(0, 5); // "Hello"
str.slice(6, 11); // "World"

// 替换
str.replace("World", "ArkTS"); // "Hello ArkTS"
str.replaceAll("o", "0"); // "Hell0 W0rld"

// 分割
str.split(" "); // ["Hello", "World"]

// 去除空格
"  Hello  ".trim(); // "Hello"
"  Hello  ".trimStart(); // "Hello  "
"  Hello  ".trimEnd(); // "  Hello"

// 重复
"Hi".repeat(3); // "HiHiHi"

// 填充
"5".padStart(3, "0"); // "005"
"5".padEnd(3, "0"); // "500"

5. JSON 操作

// 对象转 JSON 字符串
let obj = { name: "张三", age: 25 };
let jsonStr = JSON.stringify(obj);

// JSON 字符串转对象
let obj2 = JSON.parse(jsonStr);

// 格式化输出(美化)
JSON.stringify(obj, null, 2);

6. 日志输出

// console 日志
console.log("普通日志");
console.info("信息日志");
console.warn("警告日志");
console.error("错误日志");

// hilog 日志(推荐)
import hilog from "@ohos.hilog";

hilog.info(0x0000, "MyApp", "这是一条信息日志");
hilog.error(0x0000, "MyApp", "这是一条错误日志");

7. 定时器

// 延时执行
setTimeout(() => {
  console.log("1秒后执行");
}, 1000);

// 定时执行
let timer = setInterval(() => {
  console.log("每秒执行一次");
}, 1000);

// 清除定时器
clearInterval(timer);

📊 生命周期 API

组件生命周期

@Component
struct MyComponent {
  // 组件即将出现
  aboutToAppear() {
    console.log('组件即将出现')
    // 初始化数据、加载资源
  }

  // 组件即将销毁
  aboutToDisappear() {
    console.log('组件即将销毁')
    // 清理资源、取消订阅
  }

  build() {
    Column() { }
  }
}

页面生命周期

@Entry
@Component
struct IndexPage {
  // 页面即将显示
  onPageShow() {
    console.log('页面即将显示')
  }

  // 页面即将隐藏
  onPageHide() {
    console.log('页面即将隐藏')
  }

  // 返回键事件
  onBackPress() {
    console.log('点击了返回键')
    return false  // true 表示拦截返回
  }
}

🎯 常用场景 API 组合

1. 列表加载更多

@State dataList: Item[] = []
@State hasMore: boolean = true

List() {
  ForEach(this.dataList, (item: Item) => {
    ListItem() {
      ItemCard({ item: item })
    }
  })
}
.onReachEnd(() => {
  if (this.hasMore) {
    this.loadMore()  // 加载更多数据
  }
})

2. 下拉刷新

Refresh({ refreshing: this.isRefreshing }) {
  List() {
    // 列表内容
  }
}
.onRefreshing(() => {
  this.isRefreshing = true
  this.loadData().then(() => {
    this.isRefreshing = false
  })
})

3. 图片预览

Image(this.imageUrl).onClick(() => {
  // 全屏预览
  router.pushUrl({
    url: "pages/ImagePreview",
    params: { url: this.imageUrl },
  });
});

4. 表单提交

Button("提交").onClick(async () => {
  // 表单验证
  if (!this.validateForm()) {
    promptAction.showToast({ message: "请填写完整信息" });
    return;
  }

  // 发送请求
  try {
    const response = await this.submitForm();
    promptAction.showToast({ message: "提交成功" });
    router.back();
  } catch (error) {
    promptAction.showToast({ message: "提交失败" });
  }
});

📋 API 快速查找表

UI 组件

组件 作用 典型场景
Column/Row 布局容器 页面布局
Text 文本显示 标题、正文
Button 按钮 操作触发
Image 图片显示 图片展示
List 列表容器 长列表
Grid 网格布局 图片墙、商品
Swiper 轮播图 广告、相册
TextInput 文本输入 表单
Tabs 标签页 多页切换

系统能力

API 功能 典型场景
@ohos.net.http 网络请求 API 调用
@ohos.data.preferences 数据存储 配置保存
@ohos.file.fs 文件操作 文件读写
@ohos.router 路由导航 页面跳转
@ohos.promptAction 提示弹窗 Toast、对话框

工具类 API

类别 常用方法 典型场景
Array map, filter, forEach, reduce, push, splice 数据处理、列表操作
Math random, floor, ceil, round, max, min 数学计算、随机数
Date getFullYear, getMonth, getTime, formatDate 日期时间处理
String split, join, replace, trim, substring, includes 字符串处理
JSON stringify, parse 数据序列化

💡 学习建议

1. 学习路径

基础 UI 组件 → 布局容器 → 列表组件 → 系统能力 → 高级特性

2. 实践建议

  • ✅ 先掌握常用组件(Column、Row、Text、Button)
  • ✅ 学会使用 List 和 Grid 处理列表
  • ✅ 熟悉路由导航和页面跳转
  • ✅ 掌握网络请求和数据存储
  • ✅ 逐步学习动画和手势

3. 查阅文档

官方文档

  • 组件参考:https://developer.harmonyos.com/cn/docs/documentation/doc-references-V3/
  • API 参考:https://developer.harmonyos.com/cn/docs/documentation/doc-references-V3/

📚 总结

API 分层结构

ArkTS API
├─ 基础层:UI 组件(Column, Text, Button...)
├─ 能力层:系统服务(网络、存储、文件...)
├─ 框架层:路由、状态管理、生命周期
└─ 工具层:工具类、日志、定时器

核心原则

  1. UI 组件:声明式语法,链式调用
  2. 系统能力:import 导入,Promise 异步
  3. 数据驱动:状态变化自动更新 UI
  4. 生命周期:合理利用钩子函数

记忆要点

UI 组件

  • 布局用 Column/Row,列表用 List,表单用 TextInput

系统能力

  • 网络请求:@ohos.net.http
  • 数据存储:@ohos.data.preferences
  • 页面跳转:@ohos.router
  • 提示弹窗:@ohos.promptAction

工具类

  • 数组:map/filter/forEach/reduce 处理数据
  • Math:random/floor/ceil 数学计算
  • Date:getFullYear/getMonth/getTime 日期处理
  • String:split/join/replace/trim 字符串操作
  • JSON:stringify/parse 序列化

完! 🎉

Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐