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
相关推荐
namehao46514 小时前
从HarmonyOS基础认证到赋能资源建设:我的鸿蒙开发进阶之路
华为·harmonyos
前端不太难16 小时前
用一张“状态扩散图”,定位 RN 列表性能风险
react.js·harmonyos
坚持学习前端日记17 小时前
桌面端与移动端JS桥技术对比及跨平台实现
开发语言·javascript·harmonyos
彭不懂赶紧问19 小时前
鸿蒙NEXT开发浅进阶到精通15:从零搭建Navigation路由框架
前端·笔记·harmonyos·鸿蒙
不爱编程的小陈21 小时前
C/C++每日面试题
面试·职场和发展·1024程序员节
开开心心就好1 天前
右键菜单管理工具,添加程序自定义名称位置
linux·运维·服务器·ci/cd·docker·pdf·1024程序员节
钟睿1 天前
HarmonyOS弹窗+bindSheet半模态+浮层通用解决方案覆盖全业务场景
android·harmonyos
ChinaDragon1 天前
HarmonyOS:管理Cookie及数据存储
harmonyos
ChinaDragon1 天前
HarmonyOS:User-Agent开发指导
harmonyos
●VON1 天前
在 Ubuntu 24.04 上搭建 OpenHarmony(鸿蒙)PC 命令行移植开发环境
linux·学习·ubuntu·harmonyos·von