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
相关推荐
早點睡3906 小时前
高级进阶 ReactNative for Harmony项目鸿蒙化三方库集成实战:react-native-image-picker(打开手机相册)
react native·react.js·harmonyos
早點睡3906 小时前
基础入门 React Native 鸿蒙跨平台开发:react-native-easy-toast三方库适配
react native·react.js·harmonyos
前端不太难6 小时前
在 HarmonyOS 上,游戏状态该怎么“死而复生”
游戏·状态模式·harmonyos
lbb 小魔仙16 小时前
【HarmonyOS实战】OpenHarmony + RN:自定义 useValidator 表单验证
华为·harmonyos
一起养小猫18 小时前
Flutter for OpenHarmony 实战:扫雷游戏完整开发指南
flutter·harmonyos
小哥Mark20 小时前
Flutter开发鸿蒙年味 + 实用实战应用|绿色烟花:电子烟花 + 手持烟花
flutter·华为·harmonyos
前端不太难21 小时前
HarmonyOS 游戏里,Ability 是如何被重建的
游戏·状态模式·harmonyos
lbb 小魔仙21 小时前
【HarmonyOS实战】React Native 鸿蒙版实战:Calendar 日历组件完全指南
react native·react.js·harmonyos
一只大侠的侠21 小时前
Flutter开源鸿蒙跨平台训练营 Day 3
flutter·开源·harmonyos
盐焗西兰花21 小时前
鸿蒙学习实战之路-Reader Kit自定义字体最佳实践
学习·华为·harmonyos