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
相关推荐
奶糖不太甜11 小时前
鸿蒙5.1.0及ArkTS新特性
harmonyos·arkts
鸿蒙小灰11 小时前
鸿蒙开发K线图实现思路
harmonyos
小小小小小星11 小时前
鸿蒙原子化服务(Service Card)开发指南:从入门到实战
harmonyos
kymjs张涛14 小时前
零一开源|前沿技术周刊 #13
ios·harmonyos·apple
缘澄17 小时前
组件基础-List&Tabs
harmonyos
爱笑的眼睛111 天前
HarmonyOS TextArea 组件:文本输入区域的简单使用指南
华为·harmonyos
前端世界1 天前
鸿蒙异步处理从入门到实战:Promise、async/await、并发池、超时重试全套攻略
华为·harmonyos
祥睿夫子1 天前
鸿蒙ArkTS开发:Number、Boolean、String三种核心基本数据类型详解(附实战案例)
harmonyos·arkts
小喷友1 天前
第5章 高级UI与动画
前端·app·harmonyos
whysqwhw1 天前
鸿蒙ArkTS 与 Native 交互场景分类总结与关键实现
harmonyos