@BuilderParam
- @BuilderParam
- 使用舉例
- 定義模板
- 定義具體實現
- @BuilderParam初始化
- demo源碼
- 參考資料
@BuilderParam
該標簽有的作用有點類似于設計模式中的模板模式,類似于指定一個UI占位符,具體的實現交給具體的@Builder
,顧名思義,可以看出@BuilderParam是以@Builder作為參數來使用的。這么說有點讓人莫名其妙,通過例子來具體說明。
使用舉例
定義模板
如下代碼所示,定義一個顯示文本文件的@BuilderParam showMessage
方法,具體展示這個message的樣式讓客戶端來定義。
Pattern{ showMessage:(txt:string) => void;build() {Column(){//直接傳參this.showMessage("Hello HarmonyOS")}.width('30%')}
}
struct
定義具體實現
我們定義了三個@Builder
方法,分別是showMessageLineThrough
、showMessageUnderline
、showMessageUnderline
,分別展示如下圖樣式的Text
//橫線從中字體中間穿過,字體設置為紅色@Builder showMessageLineThrough(txt:string){Text() {Span(txt).fontSize(16).fontColor(Color.Red).decoration({ type: TextDecorationType.LineThrough, color: Color.Red })}.borderWidth(1).padding(10)}//下劃線,字體為斜體,顏色為藍色@Builder showMessageUnderline(txt:string){Text() {Span(txt).fontColor(Color.Blue).fontSize(16).fontStyle(FontStyle.Italic).decoration({ type: TextDecorationType.Underline, color: Color.Black })}.borderWidth(1).padding(10)}//上劃線,字體為綠色@Builder showMessageOverline(txt:string){Text() {Span(txt).fontSize(16).fontColor(Color.Green).decoration({ type: TextDecorationType.Overline, color: Color.Green })}.borderWidth(1).padding(10)}
}
@BuilderParam初始化
前面兩部構建了@BuilderParam和對應的@Builder,他們的使用方式如下代碼所示:可以看出@BuilderParam是以@Builder作為參數來使用的。
build() {Row() {//初始化@BuilderParam showMessagePattern({showMessage:this.showMessageLineThrough})Pattern({showMessage:this.showMessageUnderline})Pattern({showMessage:this.showMessageOverline})}.alignItems(VerticalAlign.Center).justifyContent(FlexAlign.SpaceAround).height('100%').width('100%')}
demo源碼
@Entry
@Component
struct Index {build() {Row() {Pattern({showMessage:this.showMessageLineThrough})Pattern({showMessage:this.showMessageUnderline})Pattern({showMessage:this.showMessageOverline})}.alignItems(VerticalAlign.Center).justifyContent(FlexAlign.SpaceAround).height('100%').width('100%')}@Builder showMessageLineThrough(txt:string){Text() {Span(txt).fontSize(16).fontColor(Color.Red).decoration({ type: TextDecorationType.LineThrough, color: Color.Red })}.borderWidth(1).padding(10)}@Builder showMessageUnderline(txt:string){Text() {Span(txt).fontColor(Color.Blue).fontSize(16).fontStyle(FontStyle.Italic).decoration({ type: TextDecorationType.Underline, color: Color.Black })}.borderWidth(1).padding(10)}@Builder showMessageOverline(txt:string){Text() {Span(txt).fontSize(16).fontColor(Color.Green).decoration({ type: TextDecorationType.Overline, color: Color.Green })}.borderWidth(1).padding(10)}
}
@Component
struct Pattern{@BuilderParam showMessage:(txt:string) => void;build() {Column(){this.showMessage("Hello HarmonyOS")}.width('30%')}
}
參考資料
@BuilderParam裝飾器:引用@Builder函數
線性布局(Row/Column)
設計模式之模版模式