ArkUI--@State装饰器

180 阅读1分钟

1.在声明式UI中,是以状态驱动视图更新:

(1)状态(State):指驱动视图更新的数据(被装饰器标记的变量)

(2)视图(View):基于UI描述渲染得到用户界面

状态.png

2.使用上需要注意的地方

(1)@State装饰器标记的变量必须进行初始化,不能为空值

(2)@State支持Object、class、string、number、boolean、enum类型以及这些类型的数组

(3)嵌套类型以及数组中的对象属性无法触发视图更新

3.具体使用案例

(1)装饰简单类型的变量

@Entry
@Component
struct Index {
  //装饰简单类型的变量
  @State isTurnOn: boolean = false
  @State msg:string = 'Hello'
  @State count:number = 0

  build() {
    Column() {
      Text(`是否开灯了:${this.isTurnOn}`)
      Text(`消息:${this.msg}`)
      Text(`当前消息的数量:${this.count}`)
      Button('Change').onClick(()=>{
        this.isTurnOn = !this.isTurnOn
        this.msg = 'Hello,World'
        this.count+=1
      })
    }.width('100%')
  }
}

(2)装饰class类型的变量以及数组

class Person {
  name:string
  age:number
  gf?:Person

  constructor(name:string,age:number,gf?:Person) {
    this.name = name
    this.age = age
    this.gf = gf
  }
}
@Entry
@Component
struct Index {
  //装饰对象
  @State p:Person = new Person('小明',18)

  //对象里面嵌套对象,改变此对象是无法立马刷新UI
  @State p2:Person = new Person('李四',20,new Person('小红',18))

  //对象数组
  @State pList:Array<Person> = [new Person('AA',18),new Person('BB',20),new Person('SS',30)]


  build() {
    Column() {
      Text(`姓名:${this.p.name},年纪:${this.p.age}`)
      Text(`${this.p2.name}的女朋友的名字叫:${this.p2.gf?.name},年纪:${this.p2.gf?.age}`)
      ForEach(this.pList,(item:Person)=>{
        Text(`name:${item.name},age:${item.age}`)
      })
      Button('改变')
        .onClick(()=>{
          this.p.age++
          //由于改的是嵌套对象的属性,所以不能引起刷新
          this.p2.gf.age++
          //数组
          //1.添加
          //this.pList.push(new Person('CC',25))
          //2.弹出
          //this.pList.pop()
          //3.splice
          // this.pList.splice(0,1)
          //4.覆盖数组的值
          // this.pList[0] = new Person('吴彦祖',18)
          //5,修改数组某个对象的值 并不能使用UI刷新
          this.pList[0].age++
        })
    }.width('100%')
  }
}