@Entry
@Component
struct BuilderCase{
// 定义响应式数据
@State formData: CardClass = {
time: "2023-12-12",
location: '回龙观',
type: '漏油'
}
// 使用builder抽离组件
@Builder
//string是一个基础数据类型,它是按值传递的,不具备响应式更新的特点
getCellContent(leftTitle: string, rightValue: string) {
Row() {
Row() {
Text(leftTitle)
Text(rightValue)
}
.width('100%')
.justifyContent(FlexAlign.SpaceBetween)
.padding({
left: 15,
right: 15
})
.borderRadius(8)
.height(40)
.backgroundColor(Color.White)
}.padding({
left: 10,
right: 10
})
}
build() {
Row() {
Column({space:10}) {
Text(JSON.stringify(this.formData))
// 复用builder抽离的组件
this.getCellContent("异常类型",this.formData.type)
this.getCellContent("异常时间",this.formData.time)
this.getCellContent("异常地址",this.formData.location)
// 点击修改数据后查看ui是否更换
Button("修改地址")
.onClick(()=>{
this.formData.location='陕西'
})
}
.width('100%')
}
.height('100%')
.backgroundColor('#ccc')
}
}
class CardClass {
time: string = ""
location: string = ""
type: string = ""
}
那是因为builder函数传入的数据是基本数据类型,不具备响应式的特点
按引用传递参数时,传递的参数可为状态变量,且状态变量的改变会引起@Builder方法内的UI刷新。ArkUI提供$$作为按引用传递参数的范式。
ABuilder( $$ : 类型 );
class CellParams {
leftTitle: string = ""
rightValue: string = ""
}
@Builder
// 也就是我们需要在builder中传入一个对象, 该对象使用$$(可使用其他字符)的符号来修饰,此时数据具备响应式了
function getCellContent($$: CellParams) {
Row() {
Row() {
Text($$.leftTitle)
Text($$.rightValue)
}
.width('100%')
.justifyContent(FlexAlign.SpaceBetween)
.padding({
left: 15,
right: 15
})
.borderRadius(8)
.height(40)
.backgroundColor(Color.White)
}.padding({
left: 10,
right: 10
})
}
那么此时复用的builde函数的参入也应该传入一个对象
Column({space:10}) {
Text(JSON.stringify(this.formData))
this.getCellContent({leftTitle:"异常类型",rightValue:this.formData.type})
this.getCellContent({leftTitle:"异常时间",rightValue:this.formData.time})
this.getCellContent({leftTitle:"异常地址",rightValue:this.formData.location})
Button("修改地址")
.onClick(()=>{
this.formData.location='陕西'
})
}