HarmonyOS鸿蒙Next中如何在class中表示两个自定义组件的父类或者泛型

HarmonyOS鸿蒙Next中如何在class中表示两个自定义组件的父类或者泛型 通过 ForEach 来生成 TabContent 里面的内容。关键代码如下:

@Entry
@Component
struct Index {
@State message: string = 'Hello World';
tabs: TabItem[] = [new TabItem(TabContentPage1('content1')), new TabItem(TabContentPage2('content2'))]

build() { 
  Tabs() { 
    ForEach(this.tabs, (item: TabItem) => { 
      TabContent() { 
        item.tabContent 
      }
      .tabBar(item.tabTitle)
    }) 
  } 
}

如何泛型的表示自定义组件,从而一个数组可以包含多个类型的自定义组件

在 iOS 中,UIView 是自定义 View 的父类,所以可以将类型指定为 UIView 从而在数组中包含多个自定义类型的 View。

更多关于HarmonyOS鸿蒙Next中如何在class中表示两个自定义组件的父类或者泛型的实战教程也可以访问 https://www.itying.com/category-93-b0.html

3 回复

鸿蒙中类和接口可以定义为泛型,而strcut装饰的自定义组件不支持泛型,建议使用联合类型,实现自定义组件类似泛型的功能。

样例写法如下:

class Data {
  aa: number = 11;
}

class Model {
  aa: string = '11';
}

type UnionData = Data | Model

@Entry
@Component
struct DatauionPage {
  array: UnionData[] = [new Data(), new Data(), new Data()];

  @Builder
  componentCloser(data: UnionData) {
    if (data instanceof Data) {
      Text(data.aa + '').fontSize(50)
    }
  }

  build() {
    Row() {
      Column() {
        ForEachCom({ arrayList: this.array, closer: this.componentCloser })
      }
      .width('100%')
    }
    .height('100%')
  }
}

@Component
export struct ForEachCom {
  arrayList: UnionData[] = [new Data(), new Data(), new Data()];
  @BuilderParam closer: (data: UnionData) => void = this.componentCloser

  @Builder
  componentCloser() {
  }

  build() {
    Column() {
      ForEach(this.arrayList, (item: UnionData) => {
        Row() {
          this.closer(item)
        }.width('100%').height(200).backgroundColor('#eee')
      })
    }
  }
}

或者可以参考文档链接如下: https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/arkts-more-cases-V5#struct支持联合类型的方案

更多关于HarmonyOS鸿蒙Next中如何在class中表示两个自定义组件的父类或者泛型的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS鸿蒙Next中,若要在class中表示两个自定义组件的父类或泛型,可以使用TypeScript的泛型机制。泛型允许在定义类、接口或函数时不指定具体类型,而是在使用时动态指定。以下是一个示例:

class ParentComponent<T, U> {
    private component1: T;
    private component2: U;

    constructor(component1: T, component2: U) {
        this.component1 = component1;
        this.component2 = component2;
    }

    public getComponent1(): T {
        return this.component1;
    }

    public getComponent2(): U {
        return this.component2;
    }
}

class CustomComponent1 {
    // 自定义组件1的实现
}

class CustomComponent2 {
    // 自定义组件2的实现
}

const parent = new ParentComponent<CustomComponent1, CustomComponent2>(new CustomComponent1(), new CustomComponent2());

在这个示例中,ParentComponent类使用了两个泛型参数TU,分别表示两个自定义组件的类型。通过这种方式,可以在实例化ParentComponent时动态指定具体组件类型,从而实现对两个自定义组件的父类或泛型表示。

在HarmonyOS鸿蒙Next中,若要在class中表示两个自定义组件的父类或泛型,可以通过继承或泛型参数来实现。若使用继承,可定义一个父类,两个自定义组件继承该类。若使用泛型,可在类定义时指定泛型参数,如 class MyClass<T extends Component>,其中 T 可以是任意组件类型。具体实现根据需求选择合适的方式。

回到顶部