HarmonyOS 组件封装问题

尝试封装一个组件如下:

@Component
export struct NormalItemContainer {
  marginLeft: number = 10;
  marginRight: number = 10;
  marginTop: number = 10;
  marginBottom: number = 0;
  contentPadding: number = 10;
  radius: number = 10;
  bgColor: string = RColor.white;
  darkBackgroundColor: string = RColor.black333;
  @StorageLink(SettingMMKVKey.darkModel) isDark: boolean = false
  @BuilderParam content: (item: object, index: number) => void;

  build() {
    Column() {
      Column() {
        ForEach(
          this.dataList,
          (item: object, index: number) => {
            this.content(item, index);
          }
        )
      }
      .width("100%")
    }
    .backgroundColor(this.isDark ? this.darkBackgroundColor : this.bgColor)
    .borderRadius(this.radius)
    .margin({
      top: this.marginTop,
      right: this.marginRight,
      bottom: this.marginBottom,
      left: this.marginLeft
    })
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.

需要传入一个datalist但是对象不确定,是否可以使用泛型。

HarmonyOS
2024-12-25 14:27:51
浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
fox280

自定义组件当前不支持泛型方式,建议方案是在自定义组件内使用联合类型方式,可以通过@Builder形式定义,用法参考以下案例:

let strArr: string[] = ["java", "python", "C++"]
let intArr: number[] = [1, 2, 3]

@Entry
@Component
struct Index {
  build() {
    Row() {
      Column() {
        this.printArray(strArr)
        Text('分割线')
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
          .fontColor(Color.Green)
        this.printArray(intArr)
      }
      .width('100%')
    }
    .height('100%')
  }

  @Builder
  printArray<T>(arr: T[]) {
    Column() {
      ForEach(arr, (item: T[]) => {
        Text(String(item))
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
      }, (item: string) => item)
    }
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
分享
微博
QQ
微信
回复
2024-12-25 16:30:25
相关问题
HarmonyOS 公共组件封装
1083浏览 • 1回复 待解决
HarmonyOS AttributeModifier封装bindPop问题
568浏览 • 1回复 待解决
HarmonyOS Span的封装问题
490浏览 • 1回复 待解决
HarmonyOSAxios封装使用问题
1239浏览 • 1回复 待解决
HarmonyOS 关于页面架构封装问题
711浏览 • 1回复 待解决
HarmonyOS 关于rcp请求封装问题
843浏览 • 1回复 待解决
HarmonyOS 自定义弹窗封装问题
929浏览 • 1回复 待解决
基于原生能力的组件封装
1394浏览 • 1回复 待解决
HarmonyOS 有RN Video组件封装吗?
1098浏览 • 1回复 待解决
HarmonyOS 自定义弹框封装问题
852浏览 • 1回复 待解决
HarmonyOS 请提供自定义组件封装demo
1414浏览 • 2回复 待解决
web组件单独封装,怎么控制处理back-
1152浏览 • 1回复 待解决
HarmonyOS CustomDialogController封装
789浏览 • 1回复 待解决