美文网首页
组件状态-更新嵌套数据

组件状态-更新嵌套数据

作者: 家乡的蝈蝈 | 来源:发表于2024-01-31 16:41 被阅读0次
@Entry
@Component
struct MultiStateCase {
  @State user:UserProfileModel = new UserProfileModel({
    username: 'xx',
    age:28,
    sex:'男',
    address: new AddressModel({
      province:'上海',
      city:'上海',
      area:'浦东'
    })
  })
  build() {
    Row() {
      Column() {
        // UI更新只能监听到第一层
        Row() {
          Text(this.user.username).fontSize(40)
          Text(this.user.age.toString()).fontSize(40)
          Text(this.user.address.province).fontSize(40)
          Text(this.user.address.city).fontSize(40)
          Text(this.user.address.area).fontSize(40)
        }
        .width('100%').height(50)
        Button('更改名字和年龄')
          .onClick(() => {
            // this.user.username = '哈哈'
            // this.user.age = 82
            this.user.address.city = '北京'
            this.user.address = new AddressModel(this.user.address)
            // this.user.address = {...this.user.address,city:'beijing'} // 延展运算在next版本只允许部分数组的更新

          })
      }
      .width('100%')
    }
    .height('100%')
  }
}

interface Address {
  province:string
  city:string
  area:string
}

interface UserProfile {
  username:string
  age:number
  sex:'男' | '女'
  address:Address
}

class AddressModel implements Address {
  province:string = ''
  city:string = ''
  area:string = ''
  constructor(model:Address) {
    this.province = model.province
    this.city = model.city
    this.area = model.area
  }
}

class UserProfileModel implements UserProfile {
  username:string = ''
  age:number = 0
  sex:'男' | '女' = '男'
  address:Address = new AddressModel({} as Address)
  constructor(model:UserProfile) {
    this.username = model.username
    this.age = model.age
    this.sex = model.sex
    this.address = model.address
  }
}

相关文章

网友评论

      本文标题:组件状态-更新嵌套数据

      本文链接:https://www.haomeiwen.com/subject/htzoodtx.html