@builder装饰器
一 介绍@Builder装饰器:自定义构建函数
用于填充UI组件
开发者可以将重复使用的UI元素抽象成一个方法,在build方法里调用。
根据场景分类
- 组件内自定义构建函数
- 全局自定义构建函数
二 问题点
以下问题时组件内自定义函数遇见的问题
在所有条件都相同的情况下,点击左边的 list更新右侧的list
方案一 使用builder ,右侧 list不会更新
方案二 直接写 list UI,右侧list会更新
所以,builder中的数据,无法双向绑定么?
getTreeItemLayout(currentList: Array<Tree>, isFirst: boolean) {
if (currentList) {
List() {
ForEach(currentList, (item: Tree) => {
ListItem() {
Text(item.name)
.width("100%")
.height(40)
.backgroundColor(isFirst ? "#ff4e79e6" : "#ffedd36f")
.maxLines(2)
.onClick(() => {
this.currentSelectItem = item
})
}
})
}.layoutWeight(1).height("100%")
}
}
更新---------------------找到解决方案了
三 解决方法
原来解决很简单。注意官方文档这句话。
看下我的问题 ,传递的时两个参数
···
@Builder
getTreeItemLayout(currentList: Array, isFirst: boolean)
···
目标是传递一个参数
因此可以 创建一个对象就完事了
改动后的如此:随便 声明一个接口,使用时把数据包住
@Builder
getTreeItemLayout(treeUI:TreeListInterface ) {
if (treeUI) {
List() {
ForEach(treeUI.currentList, (item: Tree) => {
ListItem() {
Text(item.name)
.width("100%")
.height(40)
.backgroundColor(treeUI.isFirst ? "#ff4e79e6" : "#ffedd36f")
.maxLines(2)
.onClick(() => {
this.mCurrentSelectItem = item
this.mMessage = item.name as string
})
}
})
}.layoutWeight(1)
.height("100%")
.divider({
strokeWidth: 2,
color: "#44444f"
})
}
}
如此,便可以复用 此自定义构建函数,且更新数据了。问题解决
四 仓库地址
我的仓库,欢迎来访
https://github.com/MartinLi89/WanHarmony/tree/main