鸿蒙 装饰器@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

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值