HarmonyOS Next 快速参考手册

HarmonyOS Next 快速参考手册

常用组件、API、代码片段速查表


📋 装饰器速查

组件装饰器

typescript 复制代码
@Entry              // 页面入口
@Component          // 自定义组件
@Preview            // 预览组件(开发时)

状态管理装饰器

typescript 复制代码
@State              // 组件内部状态
@Prop               // 单向传递(父→子)
@Link               // 双向绑定(父↔子)
@Provide            // 跨层级传递(祖先→后代)
@Consume            // 跨层级接收
@ObjectLink         // 嵌套对象双向绑定
@Observed           // 观察对象变化
@Watch              // 监听状态变化
@StorageLink        // 全局状态双向绑定
@StorageProp        // 全局状态单向传递

构建装饰器

typescript 复制代码
@Builder            // 自定义构建函数
@BuilderParam       // 插槽参数
@Extend             // 扩展组件样式
@Styles             // 样式集合

🎨 布局容器

Column - 垂直布局

typescript 复制代码
Column({ space: 10 }) {      // space: 子组件间距
  Text('项目1')
  Text('项目2')
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)      // 主轴对齐
.alignItems(HorizontalAlign.Center)    // 交叉轴对齐

对齐方式:

  • FlexAlign.Start - 顶部
  • FlexAlign.Center - 居中
  • FlexAlign.End - 底部
  • FlexAlign.SpaceBetween - 两端对齐
  • FlexAlign.SpaceAround - 环绕对齐
  • FlexAlign.SpaceEvenly - 平均分布

Row - 水平布局

typescript 复制代码
Row({ space: 10 }) {
  Text('项目1')
  Text('项目2')
}
.width('100%')
.justifyContent(FlexAlign.SpaceBetween)
.alignItems(VerticalAlign.Center)

Stack - 堆叠布局

typescript 复制代码
Stack({ alignContent: Alignment.TopEnd }) {
  Image($r('app.media.bg'))        // 背景层
  Column() { }                      // 内容层
  Button('浮动按钮')                // 悬浮层
}

对齐方式:

  • Alignment.TopStart - 左上
  • Alignment.Top - 顶部居中
  • Alignment.TopEnd - 右上
  • Alignment.Start - 左侧居中
  • Alignment.Center - 居中
  • Alignment.End - 右侧居中
  • Alignment.BottomStart - 左下
  • Alignment.Bottom - 底部居中
  • Alignment.BottomEnd - 右下

Flex - 弹性布局

typescript 复制代码
Flex({
  direction: FlexDirection.Row,              // 方向
  wrap: FlexWrap.Wrap,                       // 换行
  justifyContent: FlexAlign.SpaceBetween,    // 主轴对齐
  alignItems: ItemAlign.Center,              // 交叉轴对齐
  alignContent: FlexAlign.Start              // 多行对齐
}) {
  Text('项目1').flexGrow(1)    // 占据剩余空间
  Text('项目2').flexShrink(1)  // 收缩比例
}

Grid - 网格布局

typescript 复制代码
Grid() {
  ForEach(items, (item) => {
    GridItem() {
      Text(item)
    }
  })
}
.rowsTemplate('1fr 1fr 1fr')        // 3行
.columnsTemplate('1fr 1fr')         // 2列
.rowsGap(10)                        // 行间距
.columnsGap(10)                     // 列间距

List - 列表布局

typescript 复制代码
List({ space: 10 }) {
  ForEach(items, (item) => {
    ListItem() {
      Text(item)
    }
  })
}
.scrollBar(BarState.Auto)           // 滚动条
.edgeEffect(EdgeEffect.Spring)     // 边缘效果
.divider({                          // 分割线
  strokeWidth: 1,
  color: '#E0E0E0'
})

🔧 基础组件

Text - 文本

typescript 复制代码
Text('Hello World')
  .fontSize(16)                     // 字体大小
  .fontColor('#333333')             // 字体颜色
  .fontWeight(FontWeight.Bold)      // 字体粗细
  .fontFamily('Arial')              // 字体家族
  .textAlign(TextAlign.Center)      // 对齐方式
  .lineHeight(24)                   // 行高
  .maxLines(2)                      // 最大行数
  .textOverflow({                   // 溢出处理
    overflow: TextOverflow.Ellipsis
  })
  .decoration({                     // 装饰线
    type: TextDecorationType.Underline,
    color: Color.Red
  })

Image - 图片

typescript 复制代码
Image($r('app.media.icon'))
  .width(100)
  .height(100)
  .objectFit(ImageFit.Cover)        // 填充模式
  .interpolation(ImageInterpolation.High)  // 插值模式
  .sourceSize({ width: 200, height: 200 })  // 源尺寸
  .fillColor('#FF0000')             // 填充颜色(SVG)
  .alt($r('app.media.placeholder')) // 占位图

ImageFit 枚举:

  • ImageFit.Contain - 保持比例,完整显示
  • ImageFit.Cover - 保持比例,填充容器
  • ImageFit.Fill - 拉伸填充
  • ImageFit.ScaleDown - 缩小显示
  • ImageFit.None - 原始尺寸

Button - 按钮

typescript 复制代码
Button('点击')
  .type(ButtonType.Normal)          // 按钮类型
  .fontSize(16)
  .fontColor(Color.White)
  .backgroundColor('#4D91FF')
  .borderRadius(8)
  .width('100%')
  .height(48)
  .enabled(true)                    // 是否启用
  .onClick(() => {
    console.log('按钮点击')
  })

ButtonType 枚举:

  • ButtonType.Normal - 普通按钮
  • ButtonType.Capsule - 胶囊按钮
  • ButtonType.Circle - 圆形按钮

TextInput - 文本输入

typescript 复制代码
TextInput({ placeholder: '请输入' })
  .type(InputType.Normal)           // 输入类型
  .maxLength(50)                    // 最大长度
  .fontSize(16)
  .fontColor('#333333')
  .backgroundColor(Color.White)
  .borderRadius(8)
  .padding(12)
  .onChange((value: string) => {    // 输入变化
    console.log('输入值:', value)
  })
  .onSubmit(() => {                 // 提交(回车)
    console.log('提交表单')
  })

InputType 枚举:

  • InputType.Normal - 普通文本
  • InputType.Password - 密码
  • InputType.Email - 邮箱
  • InputType.Number - 数字
  • InputType.PhoneNumber - 电话号码

Checkbox - 复选框

typescript 复制代码
Checkbox()
  .select(true)                     // 是否选中
  .selectedColor('#4D91FF')         // 选中颜色
  .onChange((value: boolean) => {
    console.log('选中状态:', value)
  })

Radio - 单选框

typescript 复制代码
Row() {
  Radio({ value: 'option1', group: 'radioGroup' })
    .checked(true)
    .onChange((checked: boolean) => {
      if (checked) {
        console.log('选中 option1')
      }
    })
  Text('选项1')
}

Slider - 滑块

typescript 复制代码
Slider({
  value: 50,                        // 当前值
  min: 0,                           // 最小值
  max: 100,                         // 最大值
  step: 1                           // 步长
})
  .showSteps(true)                  // 显示步长刻度
  .showTips(true)                   // 显示提示
  .onChange((value: number) => {
    console.log('滑块值:', value)
  })

Progress - 进度条

typescript 复制代码
Progress({ value: 50, total: 100, type: ProgressType.Linear })
  .color('#4D91FF')
  .width('80%')
  .height(10)

ProgressType 枚举:

  • ProgressType.Linear - 线性进度条
  • ProgressType.Ring - 环形进度条
  • ProgressType.Eclipse - 椭圆进度条
  • ProgressType.ScaleRing - 刻度环形
  • ProgressType.Capsule - 胶囊进度条

🎯 高级组件

Tabs - 标签页

typescript 复制代码
Tabs({ barPosition: BarPosition.End }) {
  TabContent() {
    Text('首页内容')
  }.tabBar('首页')

  TabContent() {
    Text('我的内容')
  }.tabBar('我的')
}
.onChange((index: number) => {
  console.log('切换到标签:', index)
})

Swiper - 轮播

typescript 复制代码
Swiper() {
  ForEach(images, (img) => {
    Image(img)
  })
}
.loop(true)                         // 循环播放
.autoPlay(true)                     // 自动播放
.interval(3000)                     // 间隔时间
.indicator(true)                    // 显示指示器
.onChange((index: number) => {
  console.log('当前页:', index)
})
typescript 复制代码
Navigation(this.pathStack) {
  // 页面内容
}
.mode(NavigationMode.Stack)         // 导航模式
.title('页面标题')                  // 标题
.hideTitleBar(false)                // 隐藏标题栏
.hideBackButton(false)              // 隐藏返回按钮
typescript 复制代码
NavDestination() {
  Column() {
    Text('页面内容')
  }
}
.title('页面标题')
.onReady((context: NavDestinationContext) => {
  // 获取路由参数
  const params = context.pathInfo?.param
})

Scroll - 滚动容器

typescript 复制代码
Scroll() {
  Column() {
    // 长内容
  }
}
.scrollable(ScrollDirection.Vertical)  // 滚动方向
.scrollBar(BarState.Auto)              // 滚动条
.scrollBarWidth(4)                     // 滚动条宽度
.edgeEffect(EdgeEffect.Spring)         // 边缘效果
.onScroll((xOffset: number, yOffset: number) => {
  console.log('滚动偏移:', xOffset, yOffset)
})

Refresh - 下拉刷新

typescript 复制代码
Refresh({ refreshing: $$this.isRefreshing }) {
  List() {
    // 列表内容
  }
}
.onRefreshing(() => {
  // 刷新逻辑
  this.loadData()
})

🎭 渲染控制

ForEach - 循环渲染

typescript 复制代码
ForEach(
  this.items,                       // 数据源
  (item: Item, index: number) => {  // 渲染函数
    Text(item.name)
  },
  (item: Item) => item.id           // key生成函数
)

if/else - 条件渲染

typescript 复制代码
if (this.isShow) {
  Text('显示')
} else {
  Text('隐藏')
}

LazyForEach - 懒加载

typescript 复制代码
LazyForEach(
  this.dataSource,                  // 数据源(IDataSource)
  (item: Item) => {
    ListItem() {
      Text(item.name)
    }
  },
  (item: Item) => item.id
)

🎨 样式属性

尺寸

typescript 复制代码
.width(100)                         // 固定宽度
.width('50%')                       // 百分比宽度
.width('100vp')                     // vp单位
.height(100)
.aspectRatio(1)                     // 宽高比
.layoutWeight(1)                    // 权重(占据剩余空间)

边距

typescript 复制代码
.margin(10)                         // 四周
.margin({ top: 10, bottom: 10 })   // 上下
.margin({ left: 10, right: 10 })   // 左右
.padding(10)                        // 内边距

背景

typescript 复制代码
.backgroundColor('#FFFFFF')         // 背景色
.backgroundImage($r('app.media.bg')) // 背景图
.backgroundImageSize(ImageSize.Cover) // 背景图尺寸
.linearGradient({                   // 渐变
  angle: 180,
  colors: [[0xFF0000, 0.0], [0x00FF00, 1.0]]
})

边框

typescript 复制代码
.border({
  width: 1,
  color: '#E0E0E0',
  radius: 8,
  style: BorderStyle.Solid
})
.borderRadius(8)                    // 圆角

阴影

typescript 复制代码
.shadow({
  radius: 10,
  color: '#00000020',
  offsetX: 0,
  offsetY: 2
})

透明度

typescript 复制代码
.opacity(0.5)                       // 0.0 - 1.0

变换

typescript 复制代码
.rotate({ angle: 45 })              // 旋转
.scale({ x: 1.5, y: 1.5 })         // 缩放
.translate({ x: 10, y: 10 })       // 平移

位置

typescript 复制代码
.position({ x: 0, y: 0 })          // 绝对定位
.offset({ x: 10, y: 10 })          // 相对偏移

🔄 路由导航

router - 页面路由

typescript 复制代码
import { router } from '@kit.ArkUI'

// 跳转页面
router.pushUrl({ url: 'pages/DetailPage' })

// 跳转并传参
router.pushUrl({
  url: 'pages/DetailPage',
  params: { id: '123', name: '张三' }
})

// 替换当前页面
router.replaceUrl({ url: 'pages/HomePage' })

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

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

// 获取路由参数
const params = router.getParams() as Record<string, string>
typescript 复制代码
// 创建路由栈
pathStack: NavPathStack = new NavPathStack()

// 跳转
this.pathStack.pushPathByName('PageName', params)

// 返回
this.pathStack.pop()

// 清空
this.pathStack.clear()

// 获取栈大小
const size = this.pathStack.size()

💾 状态存储

AppStorage - 应用级存储

typescript 复制代码
// 设置
AppStorage.setOrCreate('key', 'value')
AppStorage.set('key', 'newValue')

// 获取
const value = AppStorage.get<string>('key')

// 删除
AppStorage.delete('key')

// 组件中使用
@StorageLink('key') value: string = ''  // 双向
@StorageProp('key') value: string = ''  // 单向

LocalStorage - 页面级存储

typescript 复制代码
// 创建
let storage = new LocalStorage({ count: 0 })

// 组件中使用
@LocalStorageLink('count') count: number = 0
@LocalStorageProp('count') count: number = 0

PersistentStorage - 持久化存储

typescript 复制代码
// 持久化数据
PersistentStorage.persistProp('token', '')

// 设置值
AppStorage.set('token', 'abc123')

// 下次启动自动恢复

🎬 动画

显式动画

typescript 复制代码
animateTo({
  duration: 1000,                   // 持续时间
  curve: Curve.EaseInOut,           // 动画曲线
  delay: 0,                         // 延迟
  iterations: 1,                    // 迭代次数(-1 无限)
  playMode: PlayMode.Normal,        // 播放模式
  onFinish: () => {                 // 完成回调
    console.log('动画完成')
  }
}, () => {
  // 状态变化
  this.scaleValue = 1.5
})

Curve 枚举:

  • Curve.Linear - 线性
  • Curve.EaseIn - 淡入
  • Curve.EaseOut - 淡出
  • Curve.EaseInOut - 淡入淡出
  • Curve.FastOutSlowIn - 快出慢入

组件内置动画

typescript 复制代码
Column()
  .width(100)
  .height(100)
  .animation({
    duration: 300,
    curve: Curve.EaseInOut
  })

转场动画

typescript 复制代码
if (this.isShow) {
  Column() { }
    .transition({
      type: TransitionType.Insert,
      opacity: 0,
      translate: { x: 0, y: 100 }
    })
}

📱 系统能力

promptAction - 提示

typescript 复制代码
import { promptAction } from '@kit.ArkUI'

// 消息提示
promptAction.showToast({
  message: '操作成功',
  duration: 2000
})

// 对话框
promptAction.showDialog({
  title: '提示',
  message: '确认删除?',
  buttons: [
    { text: '取消', color: '#999999' },
    { text: '确定', color: '#FF0000' }
  ]
}).then((data) => {
  if (data.index === 1) {
    console.log('点击确定')
  }
})

Preferences - 首选项

typescript 复制代码
import { preferences } from '@kit.ArkData'

// 获取实例
let pref = await preferences.getPreferences(context, 'myStore')

// 存储
await pref.put('key', 'value')
await pref.flush()

// 读取
let value = await pref.get('key', 'defaultValue')

// 删除
await pref.delete('key')

🛠️ 常用工具

JSON 操作

typescript 复制代码
// 对象转字符串
const jsonStr = JSON.stringify(obj)

// 字符串转对象
const obj = JSON.parse(jsonStr)

定时器

typescript 复制代码
// 延时执行
setTimeout(() => {
  console.log('延时执行')
}, 1000)

// 定时执行
const timerId = setInterval(() => {
  console.log('定时执行')
}, 1000)

// 清除定时器
clearInterval(timerId)

日期时间

typescript 复制代码
// 当前时间戳
const timestamp = Date.now()

// 日期对象
const date = new Date()
const year = date.getFullYear()
const month = date.getMonth() + 1
const day = date.getDate()
const hour = date.getHours()
const minute = date.getMinutes()

📐 单位说明

typescript 复制代码
100                 // px (像素)
'100vp'            // vp (虚拟像素,自适应)
'100fp'            // fp (字体像素,自适应)
'50%'              // 百分比
'100lpx'           // lpx (逻辑像素)

推荐使用:

  • 尺寸:vp
  • 字体:fp
  • 百分比:%

🎯 快速代码片段

基础页面模板

typescript 复制代码
@Entry
@Component
struct PageName {
  aboutToAppear() {
    // 页面加载
  }

  build() {
    Column() {
      Text('页面内容')
    }
    .width('100%')
    .height('100%')
  }
}

自定义组件模板

typescript 复制代码
@Component
export default struct ComponentName {
  @Prop data: DataType

  build() {
    Column() {
      Text('组件内容')
    }
  }
}

列表页面模板

typescript 复制代码
@Entry
@Component
struct ListPage {
  @State items: string[] = []

  build() {
    Column() {
      List({ space: 10 }) {
        ForEach(this.items, (item: string) => {
          ListItem() {
            Text(item)
          }
        })
      }
    }
  }
}

表单页面模板

typescript 复制代码
@Entry
@Component
struct FormPage {
  @State username: string = ''
  @State password: string = ''

  handleSubmit() {
    console.log('提交表单')
  }

  build() {
    Column({ space: 16 }) {
      TextInput({ placeholder: '用户名' })
        .onChange((value) => this.username = value)
      
      TextInput({ placeholder: '密码' })
        .type(InputType.Password)
        .onChange((value) => this.password = value)
      
      Button('提交')
        .onClick(() => this.handleSubmit())
    }
    .padding(24)
  }
}

📚 资源引用

typescript 复制代码
// 图片
$r('app.media.icon_name')

// 字符串
$r('app.string.app_name')

// 颜色
$r('app.color.primary_color')

// 尺寸
$r('app.float.title_font_size')

// 布尔
$r('app.boolean.is_debug')

🔍 调试技巧

typescript 复制代码
// 控制台输出
console.log('普通日志')
console.info('信息日志')
console.warn('警告日志')
console.error('错误日志')

// 对象输出
console.log('数据:', JSON.stringify(obj))

// 性能测试
const start = Date.now()
// 执行代码
const end = Date.now()
console.log('耗时:', end - start, 'ms')

📝 注意事项

命名规范

  • 文件名 : PascalCase (例: HomePage.ets)
  • 组件名 : PascalCase (例: struct HomePage)
  • 变量名 : camelCase (例: userName)
  • 常量名 : UPPER_CASE (例: MAX_COUNT)

性能优化

  • ✅ 使用 LazyForEach 处理长列表
  • ✅ 避免在 build() 中执行耗时操作
  • ✅ 合理使用 @State,避免不必要的状态
  • ✅ 图片资源使用适当尺寸
  • ✅ 及时清除定时器和监听器

常见错误

typescript 复制代码
// ❌ 错误:直接修改 @Prop
@Prop count: number
this.count++  // 报错

// ✅ 正确:使用 @Link 或回调
@Link count: number
this.count++  // 可以

// ❌ 错误:@BuilderParam 直接调用
contentBuilder: this.myBuilder()

// ✅ 正确:传递引用
contentBuilder: this.myBuilder

// ❌ 错误:忘记清除定时器
aboutToDisappear() {
  // 没有清除定时器
}

// ✅ 正确:清除定时器
aboutToDisappear() {
  clearInterval(this.timerId)
}

建议: 将此文档保存为书签,开发时随时查阅!🔖

相关推荐
流影ng2 小时前
【HarmonyOS】并发线程间的通信
typescript·harmonyos
---学无止境---3 小时前
Linux中在字符串中查找指定字符的第一次出现位置的汇编实现
linux
tianyuanwo3 小时前
虚拟机监控全攻略:从基础到云原生实战
linux·云原生·虚机监控
别或许3 小时前
在centos系统下,安装MYSQL
linux·mysql·centos
丁丁丁梦涛3 小时前
CentOS修改MySQL数据目录后重启失败的问题及解决方案
linux·mysql·centos
黑马金牌编程3 小时前
Jenkins的Linux与window部署方式
linux·运维·windows·jenkins·持续集成·cicd
web安全工具库3 小时前
告别刀耕火种:用 Makefile 自动化 C 语言项目编译
linux·运维·c语言·开发语言·数据库·算法·自动化
DechinPhy3 小时前
Ubuntu挂载新硬盘
linux·运维·服务器·ubuntu
lht6319356124 小时前
Ubuntu Server 系统安装图形界面远程工具(RDP)
linux·运维·ubuntu