HarmonyOS 状态管理V2组件的传参怎么修饰可以不设置默认值?

在ChildComponent组件中 model的接收是一定会传参数的,但是在写组件时一定让写默认值,导致很多地方都需要判空

@ObservedV2
class Person {
  age : number = 0
  name : string = '小红'

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

@Entry
@ComponentV2
struct Index {
  @Local showList : Array<Person> = [ new Person(12 , '张三') ,  new Person(28 , '李四') ]


  build() {
    Column(){
      ForEach(this.showList , (person : Person) => {
        ChildComponent({
          person : person
        })
      })
    }
  }
}

@ComponentV2
struct ChildComponent {

  person : Person | null = null
  build() {
    Column(){

    }
    .width('100%')
    .height(100)
  }
}
阅读 581
1 个回答

请参考示例:

@ObservedV2
class Person {
  age : number;
  name : string;
  constructor(age: number, name: string) {
    this.age = age;
    this.name = name;
  }
}
@Entry
@ComponentV2
struct Index {
  @Local showList : Array<Person> = [ new Person(12 , '张三') , new Person(28 , '李四') ]


  build() {
    Column(){
      ForEach(this.showList , (person : Person) => {
        ChildComponent({
          person : person
        })
      })
    }
  }
}
@ComponentV2
struct ChildComponent {

  person ?: Person | null
  build() {
    Column(){
      Text(`${this.person?.name}`)
    }
    .width('100%')
    .height(100)
  }
}