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
相关推荐
事界见闻10 小时前
鸿蒙6闪控球功能评测:盯盘、抢单、搜题,一点即达
华为·harmonyos
李二。12 小时前
ArkTS原生 | 知识问答引擎 —— 鸿蒙Next声明式UI实战
ui·华为·harmonyos
坚果的博客12 小时前
【鸿蒙 PC三方库构建系统】【测试验证】HPKCHECK文件详解
华为·harmonyos
世人万千丶12 小时前
鸿蒙PC问题解决:窗口拖动与拉伸时页面布局瞬间错乱、回弹后恢复
学习·华为·开源·harmonyos·鸿蒙·鸿蒙系统
Dream-Y.ocean12 小时前
Windows 鸿蒙 PC 应用开发:Electron 桌面级电子书阅读器开发实战指南
华为·harmonyos
浮芷.13 小时前
鸿蒙PC端 TTS 语音播放失败问题详解:从错误码到解决方案
华为·开源·harmonyos·鸿蒙·鸿蒙系统
浮芷.14 小时前
鸿蒙PC端 TTS 网络连接错误问题详解:在线/离线模式切换与网络状态管理
网络·华为·开源·harmonyos·鸿蒙·鸿蒙系统
免费gpt4分享15 小时前
我主动放弃了一半用户,只为了给剩下的人做一个95分的功能
harmonyos
世人万千丶17 小时前
鸿蒙 PC 避坑:DevEco Studio运行hdc命令执行异常完全指南
华为·开源·harmonyos·鸿蒙·鸿蒙系统
Latte Moments开发17 小时前
Harmony鸿蒙6.0实战开发项目--鸿蒙记账本(登录、注册、记账、图表)【代码在文末】
华为·harmonyos