HarmonyOS(56) 获取自定义组件的唯一ID:getUniqueId()方法

getUniqueId是API 12提供的接口,用来获取当前Component的UniqueId。UniqueId为系统为每个组件分配的Id,可保证当前应用中的唯一性。

测试代码如下,分别在PageOne、PageTwo、PageThree三个Component的aboutToAppear打印各自的UniqueId:

dart 复制代码
  aboutToAppear(): void {
    this.test();
  }
  test(){
    let uniqueId: number = this.getUniqueId();
    console.info('pageTwo uniqueId == ' + uniqueId);
  }

完整代码如下:

dart 复制代码
@Entry
@Component
struct PageOne {
  build() {
    Row() {
      Column({ space: 10 }) {
        PageTwo()
        PageThree()
      }
      .width('100%')
    }
    .height('100%')
    .backgroundColor(0xF1F3F5)
  }
  aboutToAppear(): void {
    this.test();
  }
  test(){
    let uniqueId: number = this.getUniqueId();
    console.info('pageOne uniqueId == ' + uniqueId);
  }
}
@Component
export struct PageTwo {
  @State message: string = 'Hello World 2';
  build() {
      Text(this.message)
        .id('PageTwo HelloWorld ')
        .fontSize(50)
        .fontWeight(FontWeight.Bold)

  }
  aboutToAppear(): void {
    this.test();
  }
  test(){
    let uniqueId: number = this.getUniqueId();
    console.info('pageTwo uniqueId == ' + uniqueId);
  }
}

@Component
export struct PageThree {
  @State message: string = 'Hello  World 3';

  build() {
      Text(this.message)
        .id('PageTwo HelloWorld ')
        .fontSize(50)
        .fontWeight(FontWeight.Bold)

  }
  aboutToAppear(): void {
    this.test();
  }
  test(){
    let uniqueId: number = this.getUniqueId();
    console.info('pageThree uniqueId == ' + uniqueId);
  }
}

运行后,日志输出如下所示:

dart 复制代码
10-24 10:14:56.135   46525-46525  A03D00/com.exa...simplme/JSAPP pid-46525             I     pageOne uniqueId == 3
10-24 10:14:56.136   46525-46525  A03D00/com.exa...simplme/JSAPP pid-46525             I     pageTwo uniqueId == 7
10-24 10:14:56.136   46525-46525  A03D00/com.exa...simplme/JSAPP pid-46525             I     pageThree uniqueId == 8
相关推荐
绝世番茄16 小时前
鸿蒙原生 ArkTS 布局方式之 Button+Shake 抖动按钮实战全解
华为·harmonyos·鸿蒙
●VON16 小时前
鸿蒙 PC Markdown 编辑器换行兼容:LF、CRLF 与混合换行归一化
华为·架构·编辑器·harmonyos·鸿蒙
qizayaoshuap17 小时前
# [特殊字符] 骰子模拟器 — 鸿蒙ArkTS随机算法与动画系统设计
算法·华为·harmonyos
ldsweet17 小时前
《HarmonyOS技术精讲-Basic Services Kit》电源管理进阶:亮度调节与休眠控制
华为·harmonyos
千逐6817 小时前
鸿蒙新特性 | 页面路由——router 怎么跳怎么传参
华为·harmonyos·鸿蒙
2301_7681034917 小时前
HarmonyOS趣味相机实战第19篇:CameraKit输出Profile协商、宽高比评分与会话提交
harmonyos·arkts·camerakit·photosession·设备适配
熊猫钓鱼>_>17 小时前
ArkTS 方舟编程语言 · 原创快速入门教程
运维·架构·ts·harmonyos·arkts·鸿蒙·js
小时代的大玩家18 小时前
HarmonyOS新特性-沉浸光感在叠叠消小游戏中的落地实践
前端·harmonyos
●VON18 小时前
鸿蒙 PC Markdown 编辑器查找系统:大小写、整词与循环定位
华为·单元测试·编辑器·harmonyos·鸿蒙
YM52e18 小时前
鸿蒙Flutter Stack堆叠布局:实现多层级界面
学习·flutter·华为·harmonyos·鸿蒙·鸿蒙系统