-
在声明式UI中,是以状态驱动视图更新的
状态(State): 指驱动视图更新的数据(被装饰器标记的变量)
视图(View): 基于UI描述渲染得到的用户界面
说明:
-
@state装饰器标记的变量必须初始化,不能为空值
-
@State支持Object,class,string,number,boolean、enum类型以及这些类型的数组
-
嵌套类型以及数组中的对象属性无法触发视图更新
/** * 状态管理以及那些嵌套循环下不能修改视图的更新情况 */ 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) } }