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
相关推荐
nashane11 小时前
HarmonyOS 6学习:AI攻略长截图“防抖”与像素级拼接术
学习·华为·harmonyos
想你依然心痛13 小时前
HarmonyOS 6(API 23)实战:基于悬浮导航、沉浸光感与HMAF的“代码哨兵“——AI智能体代码安全审计平台
人工智能·安全·harmonyos·智能体
轻口味14 小时前
HarmonyOS 6.1 全栈实战录 - 09 极光底座:ArkWeb 6.1 性能、安全与视觉插帧全特性深度实战
pytorch·安全·harmonyos
Ww.xh14 小时前
鸿蒙Web组件中Hash路由传登录态方案
前端·哈希算法·harmonyos
nashane14 小时前
HarmonyOS 6学习:Canvas性能优化与长截图流畅实现实战
学习·性能优化·harmonyos
轻口味15 小时前
HarmonyOS 6.1 全栈实战录 - 13 流量增长新引擎:全场景归因与 App Linking 链接深度开发实战
pytorch·深度学习·harmonyos
轻口味18 小时前
HarmonyOS 6.1 全栈实战录 - 12 性能底座与包管理演进深度开发实战
华为·harmonyos
小雨青年19 小时前
鸿蒙 HarmonyOS 6 | Pura X Max 鸿蒙原生适配 06:GridRow 做卡片自适应布局
华为·harmonyos
前端不太难20 小时前
一套鸿蒙 App,如何跑在手机 / 平板 / TV?
智能手机·电脑·harmonyos
想你依然心痛20 小时前
HarmonyOS 6(API 23)实战:基于悬浮导航、沉浸光感与HMAF的“灵犀智脑“——PC端AI智能体工作流编排平台
人工智能·华为·harmonyos·智能体