HarmonyOS --@state状态装饰器

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

HarmonyOS --@state状态装饰器_第1张图片
状态(state):指驱动视图更新的数据(被装饰器标记的变量)。
试图(view):基于UI描述渲染得到用户界面

  1. @State装饰器标记的变量必须初始化,不能为空值
  2. @State支持Object、class、string、number、boolean、enum类型以及这些类型的数据。
  3. 嵌套类型以及数组中的对象属性无法触发视图更新。

举例

@Entry  
@Component  
struct Index {  
  @State message1: string = 'Harmony'  
  @State message2: string = '遥遥领先!'  
  @State imageWidth : number = 200  
  build() {  
    Row() {  
      Column() {  
        Text(this.message1)  
          .onClick(()=>{  
            this.message1 = "hello "  
          })  
      }  
    }  
    .height('100%')  
  }  

点击文字之后,Harmony变成hello文字。

改变一个对象的状态

首先我们需要声明一个对象

// 声明一个内部类Person
class Person{  
  name:string  
  age:number  
  // 构造函数
  constructor(name:string,age:number) {  
    this.name = name  
    this.age = age  
  }  
}

// @Entry …………

// 创建一个状态修饰的对象  
  @State p:Person = new Person('Whz',21)

然后在屏幕上渲染出来

Text(`${this.p.name}:${this.p.age}`)  
  .fontSize(60)  
  .onClick(() => {  
    this.p.age++  
  })

HarmonyOS --@state状态装饰器_第2张图片
然后点击文本,年龄数值会增加1

按钮控制列表元素

import router from '@ohos.router'  
import {Header} from '../components/herder'  
// 声明一个内部类Item  
class Person{  
  name:string  
  age:number  
  
  constructor(name:string,age:number) {  
    this.name = name  
    this.age = age  
  }  
}  
@Entry  
@Component  
struct Index {  
  idx:number = 1  
  @State message1: string = 'Harmony'  
  @State message2: string = '遥遥领先!'  
  @State imageWidth: number = 200  
  
// 创建一个状态修饰的对象  
  @State p:Person = new Person('Ramos',21)  
  // 创建一个数组  
  @State list:Person[] = [  
    new Person('Rose',20),  
    new Person('White',19)  
  ]  
  build() {  
    Row() {  
      Column() {  
        Header({ title: 'Hello World' })  
        Image($r('app.media.image'))  
          .width(this.imageWidth)  
          .height(200)  
          .borderRadius(20)  
        Text(`${this.p.name}:${this.p.age}`)  
          .fontSize(60)  
          .onClick(() => {  
            this.p.age++  
          })  
          // 增加按钮逻辑
        Button('增加').onClick((event: ClickEvent) => {  
          this.list.push(new Person('人名'+ this.idx++,19))  
        })  
        ForEach(this.list,(p,index)=>{  
          Row(){  
          Text(`list中:${p.name},${p.age}`)  
          // 删除按钮逻辑
          Button('删除')  
            .onClick(()=>{  
              this.list.splice(index,1)  
            })  
            }  
          .width('90%')  
          .justifyContent(FlexAlign.SpaceAround)  
        })  
      }  
      .height('100%')  
    }  
  }}

 HarmonyOS --@state状态装饰器_第3张图片

你可能感兴趣的:(HarmonyOS4,harmonyos,华为,鸿蒙)