說明: 從 API version 9 開始,該裝飾器支持在 ArkTS 卡片中使用。
裝飾器使用說明
語法
@Extend(UIComponentName) function functionName { ... }
使用規(guī)則
? ● 和 @Styles 不同,@Extend 僅支持定義在全局,不支持在組件內(nèi)部定義。
? ● 和 @Styles 不同,@Extend 支持封裝指定的組件的私有屬性和私有事件,以及預(yù)定義相同組件的 @Extend 的方法。
// @Extend(Text)可以支持Text的私有屬性fontColor
@Extend(Text) function fancy () {
.fontColor(Color.Red)
}
// superFancyText可以調(diào)用預(yù)定義的fancy
@Extend(Text) function superFancyText(size:number) {
.fontSize(size)
.fancy()
}
? ● 和 @Styles 不同,@Extend 裝飾的方法支持參數(shù),開發(fā)者可以在調(diào)用時傳遞參數(shù),調(diào)用遵循 TS 方法傳值調(diào)用。
// xxx.ets
@Extend(Text) function fancy (fontSize: number) {
.fontColor(Color.Red)
.fontSize(fontSize)
}
@Entry
@Component
struct FancyUse {
build() {
Row({ space: 10 }) {
Text('Fancy')
.fancy(16)
Text('Fancy')
.fancy(24)
}
}
}
? ● @Extend 裝飾的方法的參數(shù)可以為 function,作為 Event 事件的句柄。
@Extend(Text) function makeMeClick(onClick: () => void) {
.backgroundColor(Color.Blue)
.onClick(onClick)
}
@Entry
@Component
struct FancyUse {
@State label: string = 'Hello World';
onClickHandler() {
this.label = 'Hello ArkUI';
}
build() {
Row({ space: 10 }) {
Text(`${this.label}`)
.makeMeClick(this.onClickHandler)
}
}
}
? ● @Extend 的參數(shù)可以為狀態(tài)變量,當(dāng)狀態(tài)變量改變時,UI 可以正常的被刷新渲染。
@Extend(Text) function fancy (fontSize: number) {
.fontColor(Color.Red)
.fontSize(fontSize)
}
@Entry
@Component
struct FancyUse {
@State fontSizeValue: number = 20
build() {
Row({ space: 10 }) {
Text('Fancy')
.fancy(this.fontSizeValue)
.onClick(() => {
this.fontSizeValue = 30
})
}
}
}
使用場景
以下示例聲明了 3 個 Text 組件,每個 Text 組件均設(shè)置了 fontStyle、fontWeight 和 backgroundColor 樣式。
@Entry
@Component
struct FancyUse {
@State label: string = 'Hello World'
build() {
Row({ space: 10 }) {
Text(`${this.label}`)
.fontStyle(FontStyle.Italic)
.fontWeight(100)
.backgroundColor(Color.Blue)
Text(`${this.label}`)
.fontStyle(FontStyle.Italic)
.fontWeight(200)
.backgroundColor(Color.Pink)
Text(`${this.label}`)
.fontStyle(FontStyle.Italic)
.fontWeight(300)
.backgroundColor(Color.Orange)
}.margin('20%')
}
}
@Extend 將樣式組合復(fù)用,示例如下。
@Extend(Text) function fancyText(weightValue: number, color: Color) {
.fontStyle(FontStyle.Italic)
.fontWeight(weightValue)
.backgroundColor(color)
}
通過 @Extend 組合樣式后,使得代碼更加簡潔,增強可讀性。
@Entry
@Component
struct FancyUse {
@State label: string = 'Hello World'
build() {
Row({ space: 10 }) {
Text(`${this.label}`)
.fancyText(100, Color.Blue)
Text(`${this.label}`)
.fancyText(200, Color.Pink)
Text(`${this.label}`)
.fancyText(300, Color.Orange)
}.margin('20%')
}
}
審核編輯 黃宇
-
API
+關(guān)注
關(guān)注
2文章
2283瀏覽量
66535 -
鴻蒙
+關(guān)注
關(guān)注
60文章
2924瀏覽量
45575 -
OpenHarmony
+關(guān)注
關(guān)注
33文章
3942瀏覽量
20914
發(fā)布評論請先 登錄
【OpenHarmony快速入門】本期視頻將介紹應(yīng)用開發(fā)初學(xué)者如何構(gòu)建一個簡單的應(yīng)用。
無法定位和自定義組件怎么解決?
關(guān)于生命周期中的aboutToAppear和onPageShow的理解和應(yīng)用
HarmonyOS基礎(chǔ)組件:Button三種類型的使用
OpenHarmony 定義擴展組件樣式:@Extend 裝飾器
評論