学习鸿蒙第四课(@state装饰器)

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

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

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

说明:

  1. @state装饰器标记的变量必须初始化,不能为空值

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

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

    /**
     * 状态管理以及那些嵌套循环下不能修改视图的更新情况
     */
    class Student{
       name:string
       age:number
       gsGirl:Student
      constructor(name:string,age:number,gsGril?:Student) {
        this.name = name
        this.age = age
        this.gsGirl = gsGril
      }
    }
    @Entry
    @Component
    struct Index {
      @State private GirlList:Array<Student> = [
        new Student('Jack',12),
        new Student('Jack',12),
        new Student('Jack',12),
        new Student('Jack',12),
      ]
      @State p: Student = new Student('Jack',12,new Student('gril',77))
      @State index:number = 1
    
      build() {
          Column() {
            Row() {
            Text(`${this.p.gsGirl.name} ---- ${this.p.gsGirl.age}`)
              .fontSize(50)
              .fontWeight(FontWeight.Bold)
              .fontColor('#35D')
              .onClick(() => {
                 // error错误不可修改深度对象中的值
                 //  this.p.gsGirl.age++
              })
    
          }
            Row() {
              Text('---女友列表--')
                .fontSize(30)
                .fontWeight(FontWeight.Bold)
                .fontColor('#35D')
    
            }
            Button('添加女友')
              .onClick(()=>{
                this.GirlList.push(new Student(`欣儿${this.index++}`,99))
              })
            ForEach(
              this.GirlList,
              (item:Student,index)=>{
                Row(){
                  Text(`${item.name} ==  ${item.age}`)
                    .fontSize(30)
                    .fontWeight(FontWeight.Bold)
                    .fontColor('#35D')
                    .margin({right:20})
                    .onClick(() => {
                      this.GirlList[index] = new Student(item.name,item.age++)
                    })
                  Button('删除女友')
                    .onClick(()=>{
                      this.GirlList.splice(index,1)
                    })
                }
                .margin({bottom:20})
              }
            )
    
    
        }
        .width('100%')
        .justifyContent(FlexAlign.Center)
    
    
      }
    }
    
  • 5
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值