当前位置:   article > 正文

harmonyOS学习笔记之状态修饰器@state,@prop,@link_鸿蒙os @state

鸿蒙os @state

@State:
1.@State装饰的变量拥有其所属组件的状态,可以作为其子组件单向和双向同步的数据源. 当其数值改变时,会引起相关组件的渲染刷新.
2.其声明的变量必须初始化值.
@Prop:
1.@Prop装饰的变量可以和父组件建立单向同步关系.
2.@Prop装饰的变量是可变的,但修改不会同步回父组件。.
3.其声明的变量不允许初始化值.
@Link:
1.@Link装饰的变量和父组件构建双向同步关系的状态变量,父组件会接受来自@Link装饰的变量的修改的同步,父组件的更新也会同步给@Link装饰的变量

@Entry
@Component
struct StateManage {
  // @State 声明的变量必须初始化值
  @State name: string = '小明'
  @State age: number = 11
  @State msg: string = '我是初始化数据'
  @State clickContent: string = '点我!点我!!!'
  build() {
    Row() {
      Column() {
        Text(this.name+'今年'+this.age+'岁')
          .StateManage_textSty(Color.Yellow)
        Text(this.msg)
          .StateManage_textSty(Color.Pink)
        Button(this.clickContent)
          .StateManage_btnStyCli(()=>{
              this.msg = this.age === 18 ? this.name + '成年啦' : this.name + '还没成年呢'
              this.age = this.age === 18 ? 11 : 18
          })
        Divider()
        StateManagePropItem({content_Prop:this.msg}) //调用的时候必须初始化参数
        Divider()
        // 如果是@State <----> @Link 参数传递时,使用$变量名进行传值
        StateManageLinkItem({content_Link:$msg})
      }
      .width('100%')
    }
    .height('100%')
  }
}
@Component
struct StateManagePropItem{
  //@Prop 装饰的状态数据,方便父子组件之间进行数据传递和同步
  //其声明的变量不允许初始化值
  //单向传递 @State --> @Prop
  @Prop content_Prop: string
  build(){
    Column(){
      Text('Prop:'+this.content_Prop)
        .StateManage_textSty(Color.Red)
      Button('修改Prop数据')
        .StateManage_btnStyCli(()=>{
          this.content_Prop = "Prop数据"
        })

    }
  }
}
@Component
struct StateManageLinkItem{
  @Link content_Link:string
  build(){
    Column(){
      Text('Link:'+this.content_Link).StateManage_textSty()
      Button('修改Link数据').StateManage_btnStyCli(()=>{
        this.content_Link = 'Link数据'
      })
    }
  }
}

@Extend(Text) function StateManage_textSty(color?:Color){
  .fontSize(30)
  .fontWeight(FontWeight.Bold)
  .fontColor(color)
}
@Extend(Button) function StateManage_btnStyCli(click:()=>void) {
  .fontSize(30)
  .onClick(() => {
    click()
  })
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73

后续还有补充

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】
推荐阅读
相关标签
  

闽ICP备14008679号