@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
}
}
网友评论