当前位置: 首页 > news >正文

HarmonyOS Next 快速参考手册

HarmonyOS Next 快速参考手册

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


📋 装饰器速查

组件装饰器

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

状态管理装饰器

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

构建装饰器

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

🎨 布局容器

Column - 垂直布局

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 - 水平布局

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

Stack - 堆叠布局

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 - 弹性布局

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 - 网格布局

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

List - 列表布局

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

🔧 基础组件

Text - 文本

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 - 图片

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 - 按钮

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 - 文本输入

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 - 复选框

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

Radio - 单选框

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

Slider - 滑块

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

Progress - 进度条

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 - 标签页

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

Swiper - 轮播

Swiper() {ForEach(images, (img) => {Image(img)})
}
.loop(true)                         // 循环播放
.autoPlay(true)                     // 自动播放
.interval(3000)                     // 间隔时间
.indicator(true)                    // 显示指示器
.onChange((index: number) => {console.log('当前页:', index)
})

Navigation - 导航

Navigation(this.pathStack) {// 页面内容
}
.mode(NavigationMode.Stack)         // 导航模式
.title('页面标题')                  // 标题
.hideTitleBar(false)                // 隐藏标题栏
.hideBackButton(false)              // 隐藏返回按钮

NavDestination - 导航目标

NavDestination() {Column() {Text('页面内容')}
}
.title('页面标题')
.onReady((context: NavDestinationContext) => {// 获取路由参数const params = context.pathInfo?.param
})

Scroll - 滚动容器

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

Refresh - 下拉刷新

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

🎭 渲染控制

ForEach - 循环渲染

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

if/else - 条件渲染

if (this.isShow) {Text('显示')
} else {Text('隐藏')
}

LazyForEach - 懒加载

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

🎨 样式属性

尺寸

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

边距

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

背景

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

边框

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

阴影

.shadow({radius: 10,color: '#00000020',offsetX: 0,offsetY: 2
})

透明度

.opacity(0.5)                       // 0.0 - 1.0

变换

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

位置

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

🔄 路由导航

router - 页面路由

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>

Navigation - 导航栈

// 创建路由栈
pathStack: NavPathStack = new NavPathStack()// 跳转
this.pathStack.pushPathByName('PageName', params)// 返回
this.pathStack.pop()// 清空
this.pathStack.clear()// 获取栈大小
const size = this.pathStack.size()

💾 状态存储

AppStorage - 应用级存储

// 设置
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 - 页面级存储

// 创建
let storage = new LocalStorage({ count: 0 })// 组件中使用
@LocalStorageLink('count') count: number = 0
@LocalStorageProp('count') count: number = 0

PersistentStorage - 持久化存储

// 持久化数据
PersistentStorage.persistProp('token', '')// 设置值
AppStorage.set('token', 'abc123')// 下次启动自动恢复

🎬 动画

显式动画

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 - 快出慢入

组件内置动画

Column().width(100).height(100).animation({duration: 300,curve: Curve.EaseInOut})

转场动画

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

📱 系统能力

promptAction - 提示

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 - 首选项

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 操作

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

定时器

// 延时执行
setTimeout(() => {console.log('延时执行')
}, 1000)// 定时执行
const timerId = setInterval(() => {console.log('定时执行')
}, 1000)// 清除定时器
clearInterval(timerId)

日期时间

// 当前时间戳
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()

📐 单位说明

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

推荐使用:

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

🎯 快速代码片段

基础页面模板

@Entry
@Component
struct PageName {aboutToAppear() {// 页面加载}build() {Column() {Text('页面内容')}.width('100%').height('100%')}
}

自定义组件模板

@Component
export default struct ComponentName {@Prop data: DataTypebuild() {Column() {Text('组件内容')}}
}

列表页面模板

@Entry
@Component
struct ListPage {@State items: string[] = []build() {Column() {List({ space: 10 }) {ForEach(this.items, (item: string) => {ListItem() {Text(item)}})}}}
}

表单页面模板

@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)}
}

📚 资源引用

// 图片
$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')

🔍 调试技巧

// 控制台输出
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,避免不必要的状态
  • ✅ 图片资源使用适当尺寸
  • ✅ 及时清除定时器和监听器

常见错误

// ❌ 错误:直接修改 @Prop
@Prop count: number
this.count++  // 报错// ✅ 正确:使用 @Link 或回调
@Link count: number
this.count++  // 可以// ❌ 错误:@BuilderParam 直接调用
contentBuilder: this.myBuilder()// ✅ 正确:传递引用
contentBuilder: this.myBuilder// ❌ 错误:忘记清除定时器
aboutToDisappear() {// 没有清除定时器
}// ✅ 正确:清除定时器
aboutToDisappear() {clearInterval(this.timerId)
}

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

http://www.dtcms.com/a/490454.html

相关文章:

  • 8.list的模拟实现
  • 鸿蒙NEXT按键拦截与监听开发指南
  • 网站建设等级定级企查查官网查企业网页版
  • 【数据结构】基于Floyd算法的最短路径求解
  • 【传感器技术】入门红外传感器技术
  • 成都哪里做网站便宜郴州新网招聘官网
  • 天地一体:卫星互联网与5G/6G的融合之路
  • BCH码编译码仿真与误码率性能分析
  • 5G+AIoT智赋,AI电力加密边缘网关智慧电网数字化运维解决方案
  • 深度学习:PyTorch Lightning,训练流程标准化?
  • 100G 单纤光模块:高带宽传输新选择,选型与应用全解析
  • 网站开发的技术有gis网站开发实战教程
  • 汕头网站建设技术外包模板网站怎么用
  • 2025-10-16-TH 开源框架JeecgBoot Pro搭建流程
  • 二叉树搜索树插入,查找,删除,Key/Value二叉搜索树场景应用+源码实现
  • 2025年10月版集成RagFlow和Dify的医疗知识库自动化查询(数据篇)
  • UVa 12803 Arithmetic Expressions
  • json转excel xlsx文件
  • 【C++】深入理解string类(5)
  • 六、Hive的基本使用
  • 铜陵网站建设推广江苏核酸检测机构
  • 电子商务网站建设含义如果做车站车次查询的网站需要什么消息信息
  • 【JETSON+FPGA+GMSL】实测分享 | 如何实现激光雷达与摄像头高精度时间同步?
  • 建网站权威公司dw怎么做打开网站跳出提示
  • 阅读:REACT: SYNERGIZING REASONING AND ACTING INLANGUAGE MODELS(在语言模型中协同推理与行动)
  • 语义三角论对AI自然语言处理中深层语义分析的影响与启示
  • SpringBoot 启动时执行某些操作的 8 种方式
  • Cloud IDE vs 本地IDE:AI编程时代的“降维打击“
  • RocketMQ 事务消息
  • 做网站的不肯给ftp企业163邮箱登录