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
相关推荐
用户593096009782 小时前
Flutter 鸿蒙化实战:r_upgrade 适配 OpenHarmony,应用升级检查与弹窗
harmonyos
youyin2 小时前
HarmonyOS 鸿蒙 ArkTS/ArkUI 装饰器大全
华为·harmonyos
轻口味2 小时前
HarmonyOS 7 新特性1:闪控窗——轻规划里的专注倒计时,跟着你走出应用
harmonyos·鸿蒙·移动端·闪控窗
用户593096009782 小时前
Flutter 鸿蒙化实战:record_mp3 适配 OpenHarmony,边录音边出 MP3
harmonyos
youyin3 小时前
HarmonyOS ArkTS 与智能融合案例之实时语音翻译应用 实验指导书和代码
华为·harmonyos
木子雨廷3 小时前
第 16 天|网络四态:loading、error、empty、content
harmonyos
用户593096009783 小时前
Flutter 鸿蒙化实战:open_app_settings 适配 OpenHarmony,一键跳转系统设置
harmonyos
贾伟康3 小时前
【HarmonyOS 7新能力|047】ModularObjectExtensionAbility工程封装:把接入逻辑放进可维护的分层结构
harmonyos·arkts·模块化架构·跨应用调用·abilitykit
李游Leo4 小时前
HarmonyOS 7 ArkTS 并发实战:Sendable、共享模块与跨线程对象传递机制
harmonyos
骑着蜗牛撵大象3275 小时前
从跨平台Linux到鸿蒙PC:基于Qt C++的Flameshot截图工具源码级适配
harmonyos·鸿蒙·es