getUniqueId是API 12提供的接口,用来获取当前Component的UniqueId。UniqueId为系统为每个组件分配的Id,可保证当前应用中的唯一性。
测试代码如下,分别在PageOne、PageTwo、PageThree三个Component的aboutToAppear打印各自的UniqueId:
aboutToAppear(): void {this.test();}test(){let uniqueId: number = this.getUniqueId();console.info('pageTwo uniqueId == ' + uniqueId);}
完整代码如下:
{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);}
}
export struct PageTwo { 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);}
}
export struct PageThree { 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);}
}
struct PageOne
运行后,日志输出如下所示:
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