当前位置:   article > 正文

HarmonyOS --@state状态装饰器_harmonyos @state

harmonyos @state

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


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

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

举例

  1. @Entry
  2. @Component
  3. struct Index {
  4. @State message1: string = 'Harmony'
  5. @State message2: string = '遥遥领先!'
  6. @State imageWidth : number = 200
  7. build() {
  8. Row() {
  9. Column() {
  10. Text(this.message1)
  11. .onClick(()=>{
  12. this.message1 = "hello "
  13. })
  14. }
  15. }
  16. .height('100%')
  17. }

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

改变一个对象的状态

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

  1. // 声明一个内部类Person
  2. class Person{
  3. name:string
  4. age:number
  5. // 构造函数
  6. constructor(name:string,age:number) {
  7. this.name = name
  8. this.age = age
  9. }
  10. }
  11. // @Entry …………
  12. // 创建一个状态修饰的对象
  13. @State p:Person = new Person('Whz',21)

然后在屏幕上渲染出来

  1. Text(`${this.p.name}:${this.p.age}`)
  2. .fontSize(60)
  3. .onClick(() => {
  4. this.p.age++
  5. })


然后点击文本,年龄数值会增加1

按钮控制列表元素

  1. import router from '@ohos.router'
  2. import {Header} from '../components/herder'
  3. // 声明一个内部类Item
  4. class Person{
  5. name:string
  6. age:number
  7. constructor(name:string,age:number) {
  8. this.name = name
  9. this.age = age
  10. }
  11. }
  12. @Entry
  13. @Component
  14. struct Index {
  15. idx:number = 1
  16. @State message1: string = 'Harmony'
  17. @State message2: string = '遥遥领先!'
  18. @State imageWidth: number = 200
  19. // 创建一个状态修饰的对象
  20. @State p:Person = new Person('Ramos',21)
  21. // 创建一个数组
  22. @State list:Person[] = [
  23. new Person('Rose',20),
  24. new Person('White',19)
  25. ]
  26. build() {
  27. Row() {
  28. Column() {
  29. Header({ title: 'Hello World' })
  30. Image($r('app.media.image'))
  31. .width(this.imageWidth)
  32. .height(200)
  33. .borderRadius(20)
  34. Text(`${this.p.name}:${this.p.age}`)
  35. .fontSize(60)
  36. .onClick(() => {
  37. this.p.age++
  38. })
  39. // 增加按钮逻辑
  40. Button('增加').onClick((event: ClickEvent) => {
  41. this.list.push(new Person('人名'+ this.idx++,19))
  42. })
  43. ForEach(this.list,(p,index)=>{
  44. Row(){
  45. Text(`list中:${p.name},${p.age}`)
  46. // 删除按钮逻辑
  47. Button('删除')
  48. .onClick(()=>{
  49. this.list.splice(index,1)
  50. })
  51. }
  52. .width('90%')
  53. .justifyContent(FlexAlign.SpaceAround)
  54. })
  55. }
  56. .height('100%')
  57. }
  58. }}

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/256803
推荐阅读
相关标签
  

闽ICP备14008679号