HarmonyOS 鸿蒙Next 父子组件传递数组、渲染UI页面问题

HarmonyOS 鸿蒙Next 父子组件传递数组、渲染UI页面问题

我想在父组件中传递一整个一维数组到子组件,在子组件中去遍历。如果在父组件中增减了数组中的对象可以同步刷新子组件的页面,这种场景该怎么实现啊?

3 回复

这边写了一个demo,向子组件传递对象数组,增减对象可刷新页面。可以参考一下:

//Person类
class Person {
  public id: number;
  public name: string;

  constructor(id:number,name:string) {
    this.id = id;
    this.name = name;
  }
}

//子组件
@Component
struct Child {
  @Link personArr: Person[];
  build() {
    Column({space:5}) {
      Text('人员列表')
      List({ space: 20, initialIndex: 0 }) {
        ForEach(this.personArr, (item: Person) => {
          ListItem() {
            Text(){
              Span('id:'+item.id)
              Span('---')
              Span('姓名:'+item.name)
            }
            .width('100%').backgroundColor(Color.White).padding(10)
          }
        }, (item: Person) => item.id.toString())
      }
      .listDirection(Axis.Vertical) // 排列方向
      .width('90%')
    }
    .width('100%')
    .padding({ top: 5 })
  }
}

//父组件
@Entry
@Component
struct Index {
  @State persons: Person[] = [new Person(1,'张三1')];
  @State myId: number = 2;
  build() {
      Column({space:10}) {
        Child({personArr:this.persons})
        Button('增加人员')
          .onClick(()=>{
            this.persons.push(new Person(this.myId,'张三'+this.myId))
            this.myId++;
          })

        Button('减少人员')
          .onClick(()=>{
            this.persons.pop()
          })
      }
      .width('100%')
      .height('100%')
      .backgroundColor(Color.Pink)
  }
}

更多关于HarmonyOS 鸿蒙Next 父子组件传递数组、渲染UI页面问题的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


子组件用[@Link](/user/Link)?

在HarmonyOS 鸿蒙Next中,父子组件传递数组并渲染UI页面,可以通过以下方式实现:

  1. 数据绑定

    • 父组件定义并初始化数组数据。
    • 使用@Consume注解在子组件中接收父组件传递的数据。
  2. 数据传递

    • 父组件在模板中通过自定义属性将数组数据传递给子组件。
    • 子组件接收数组数据后,可以通过@Link注解或@State注解进行状态管理。
  3. 渲染UI

    • 子组件接收数组后,利用ForEach组件遍历数组并渲染每个元素。
    • 渲染过程中,可以根据数组元素的数据类型和内容,使用相应的UI组件(如TextImage等)进行展示。
  4. 示例代码

    • 父组件:
      <ChildComponent arrayData="{{parentArray}}"/>
      
      this.parentArray = [1, 2, 3, 4, 5];
      
    • 子组件:
      <ForEach items="{{arrayData}}" item="item">
        <Text>{{item}}</Text>
      </ForEach>
      
      @Consume('arrayData') arrayData;
      

如果问题依旧没法解决请联系官网客服,官网地址是:https://www.itying.com/category-93-b0.html

回到顶部