HarmonyOS状态管理:@State与@Prop、@Link的示例

336 阅读1分钟

“本文正在参加华为鸿蒙有奖征文征文活动”

参考官方文档:developer.huawei.com/consumer/cn…

@State与@Prop

  • 父子组件之间进行数据传递和同步
  • 单向传递,State-->Prop 父只能传递给子
//父的数据只能传给子
//State --->Prop  单向的
@Component
struct upProp {
 //子
 @Prop content_prop: string

 build() {
   Column() {
     Text('Prop:' + this.content_prop)
       .textSty()
     Button('修改prop数据')
       .btnSty(() => {
         this.content_prop = '我是单向的'
       })
   }

 }
}

@State与@Link

  • 父子组件之间进行数据传递和同步
  • 双向传递,State<-->Link
//存放一个 @Link装饰的状态数据
//双向的
@Component
struct upLink {
  //子
  @Link content_link: string

  build() {
    Column() {
      Text(`Link:${this.content_link}`)
        .textSty()
      Button('修改link数据')
        .btnSty(() => {
          this.content_link = '我是双向的'
        })
    }
  }
}

完整示例:

@Entry
@Component
struct testState {
  //父
  @State name: string = "JasonYin"

  build() {
    Column({ space: 0 }) {
      Text(this.name)
        .textSty()
      Divider()
      Button('点我点我')
        .btnSty(() => {
          this.name = this.name === 'JasonYin' ? 'HarmonyOS4.0' : 'JasonYin'
        })
      Divider()
      upProp({ content_prop: this.name })
      Divider()
      //如果是 state < --- > link 参数传递时,使用 $变量名 进行传递
      upLink({ content_link: $name })
    }

  }
}

//父的数据只能传给子
//State --->Prop  单向的
@Component
struct upProp {
  //子
  @Prop content_prop: string

  build() {
    Column() {
      Text('Prop:' + this.content_prop)
        .textSty()
      Button('修改prop数据')
        .btnSty(() => {
          this.content_prop = '我是单向的'
        })
    }

  }
}

//存放一个 @Link装饰的状态数据
//双向的
@Component
struct upLink {
  //子
  @Link content_link: string

  build() {
    Column() {
      Text(`Link:${this.content_link}`)
        .textSty()
      Button('修改link数据')
        .btnSty(() => {
          this.content_link = '我是双向的'
        })
    }
  }
}

@Extend(Button) function btnSty(click: Function) {
  .fontSize(33)
  .onClick(() => {
    click()
  })
}

@Extend(Text) function textSty() {
  .fontSize(30)
  .fontWeight(FontWeight.Bold)
  .fontColor(Color.Green)
}