1开镣、自定義構建函數
1.1、構建函數- @BuilderParam 傳遞UI
● Component可以抽提組件
● Builder可以實現輕量級的UI復用
● BuilderParam只能應用在Component組件中沿盅,不能使用Entry修飾的組件中使用。類似vue里面的slot插槽
語法: @BuilderParam name: () => void
聲明一個Card組件
@Component
struct Card {
@BuilderParam // 代表插槽的參數
content: () => void = () => {}
build() {
Column() {
if (this.content) {
this.content() // 渲染傳入的內容
}
父組件調用傳入
@Entry
@Component
struct BuilderParamCase {
@Builder // 定義插槽
getContent () {
Row() {
Text("插槽內容")
.fontColor(Color.Red)
}
}
build() {
Row() {
Column() {
// 需要注意的是,傳入的函數必須是使用Builder修飾符修飾的
Card({ content: this.getContent }) // 調用子組件疾渣,并把插槽作為參數傳入
}
.width('100%')
}
.height('100%')
}
}
BuilderParams類似于 Vue中的插槽
- 子組件中定義一個用BuilderParam修飾的函數
- 父組件需要給子組件傳入一個用Builder修飾的函數來賦值給子組件
- 子組件要在想要顯示插槽的地方來調用傳入的方法
1.1.1拴魄、尾隨閉包
??當我們的組件只有一個BuilderParam的時候冗茸,此時可以使用尾隨閉包的語法 也就是像我們原來使用Column或者Row組件時一樣,直接在大括號中傳入匹中, 如下
Card() {
Text('1')
this.renderButton()
}
??如果有多個BuilderParam夏漱,你必須在組件的函數中老老實實的傳入多個builder自定義函數
@Component
struct Card {
@BuilderParam
content: () => void // 傳入多個builder自定義函數
@BuilderParam
header: () => void // 傳入多個builder自定義函數
build() {
Column () {
if(this.header) {
this.header()
}
if(this.content) {
this.content()
}
}
}
}
@Entry
@Component
struct BuilderParamCase {
@Builder
getContent () {
Row() {
Text("插槽內容")
.fontColor(Color.Red)
}
}
@Builder
getHeader () {
Row() {
Text("頭部內容")
.fontColor(Color.Red)
}
}
build() {
Row() {
Column() {
Card({
header: () => { // 傳入多個builder自定義函數
this.getHeader()
},
content: () => { // 傳入多個builder自定義函數
this.getContent()
}
})
}
.width('100%')
}
.height('100%')
}
}
案例- 封裝Card 和CardItem組件, 使用BuilderParam屬性完成插槽傳參
@Entry
@Component
struct BuildParamCard {
@State message: string = 'Hello World'
@Builder
getCardItem() {
CardItem({leftTitle:'員工姓名', rightTitle:'張三'})
CardItem({leftTitle:'員工上級', rightTitle:'李四', showBottomBorder:false})
}
build() {
Row() {
Column() {
Card2({CardFn:this.getCardItem})
}
.width('100%')
}
.height('100%')
.backgroundColor(Color.Gray)
}
}
@Component
struct Card2 {
@BuilderParam
CardFn: () => void = () => {}
build() {
Column() {
Column() {
// 傳插槽內容
this.CardFn()
}
.backgroundColor(Color.White)
.width('100%')
.borderRadius(8)
}.margin({
top:10
})
.padding({
left:15,
right:15
})
}
}
@Component
struct CardItem {
leftTitle:string = ""
rightTitle:string = ""
showBottomBorder:boolean = true
build() {
Row() {
Text(this.leftTitle)
Text(this.rightTitle).fontColor("#ccc")
}
.width('100%')
.justifyContent(FlexAlign.SpaceBetween)
.padding({
left:10,
right:10
})
.height(50)
.border({
color:'#f4f5f6',
width:{
bottom:this.showBottomBorder ? 1 :0 //下劃線
}
})
}
}