// 定义class类
class Person {
  private name: string;

  constructor(name: string) {
    this.name = name
  }

  public getInfo(): string {
    return `姓名:${this.name}`
  }
}
//------------ 自定义子组件------------
@Component
struct myChild {
  //---------------   定义状态值----------------
  // @Prop装饰器-父子单向同步,可初始化,若没有初始化父组件需传值
  @Prop age: number
  @State name: string = 'jock'
  //  @Link-父子双向同步,传值需加$,this.也可以,编辑器会报红,禁止本地初始化
  @Link bodyHeight: number

  build() {
    Column() {
      Text(`我是子组件`).fontColor(Color.Red)
      Button('改变身高').onClick(() => {
        this.bodyHeight += 10
      })
      Text(`姓名:${this.name}年龄:${this.age}身高:${this.bodyHeight}`)

    }
  }
}
//-------------------- 主页面------------------------------------
@Entry //入口文件,表示主页面
@Component //自定义组件
struct homeName { //定义组件名字
  //---------------   定义状态值----------------
  // @State 需指定其类型和本地初始化,私有动态值,场景:简单类型,装饰Class对象类型的变量
  @State age: number = 14
  @State people: Person = new Person('张三')
  @State body: number = 165
  // 私有不动态常量
  private addNum: number = 1

  build() {
    Column() {
      Text(`${this.age}`)
      Divider()
      Text(`${this.people.getInfo()},身高:${this.body}`)
      Button('改变身高').onClick(() => {
        this.body += 10
      })
      Divider()
      Text(`下面是子组件`)
      myChild({ age: this.age, name: '11lili', bodyHeight: $body })
    }
  }
}

Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐