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
相关推荐
君莫笑1111120 分钟前
从零到一教你在鸿蒙中实现微信分享--全流程
前端·harmonyos
天生我材必有用_吴用3 小时前
鸿蒙开发入门到进阶:从布局基础到组件实战
前端·harmonyos·arkts
悬空八只脚4 小时前
React-Native开发鸿蒙NEXT-svg绘制睡眠质量图part3
harmonyos
坚果的博客20 小时前
坚果派已适配的鸿蒙版flutter库【持续更新】
flutter·华为·开源·harmonyos
NapleC21 小时前
HarmonyOS:Navigation实现导航之页面设置和路由操作
华为·harmonyos·navigation
HMSCore21 小时前
HarmonyOS SDK助力鸿蒙版今日水印相机,真实地址防护再升级
harmonyos
风中飘爻1 天前
鸿蒙生态:鸿蒙生态校园行心得
华为·harmonyos
Otaku_尻男1 天前
HarmonyOS 自定义RenderNode 绘图实战
android·面试·harmonyos