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
相关推荐
shenshizhong2 小时前
鸿蒙南向开发 编写一个简单子系统
前端·harmonyos
HarmonyOS_SDK5 小时前
一碰即传,重构跨设备文件分享体验
harmonyos
lzb_kkk5 小时前
【实习总结】Qt通过Qt Linguist(语言家)实现多语言支持
开发语言·c++·qt·1024程序员节·qt linguist·qt 语言家
zhanshuo21 小时前
让鸿蒙应用飞起来!ArkUI 图形渲染性能优化全攻略
harmonyos
zhanshuo1 天前
在 ArkUI 中实现丝滑嵌套滚动:让你的页面像抖音一样顺滑
harmonyos
simple_lau1 天前
鸿蒙开发中如何快速定位丢帧
harmonyos·arkts·arkui
云_杰1 天前
利用AI开发我又又上架了一个鸿蒙产品——青蓝程序员工具箱
harmonyos·trae
萤火虫儿飞飞1 天前
鸿蒙智选携手IAM进驻长隆熊猫村,为国宝打造智慧健康呼吸新空间
华为·harmonyos
御承扬1 天前
HarmonyOS NEXT系列之定制化构建制品
华为·harmonyos
大土豆的bug记录1 天前
鸿蒙拉起系统定位和app授权定位
前端·javascript·harmonyos