鸿蒙Harmony(八)ArkUI--状态管理器之@State

news/2024/8/19 11:34:39

状态管理

在声明式UI中,是以状态驱动视图更新
状态:指驱动视图更新的数据(被装饰器标记的变量)

  • @State
  • @Prop 和 @Link
  • @Provide和 @Consume

@State

  • @State装饰器标记的变量必须初始化,不能为空值
  • @State支持Object 、class、string、number、boolean、enum 类型以及这些类型的数组
  • 嵌套类型以及数组中的对象属性无法触发视图更新
    无法触发视图更新的代码示例如下:

嵌套类型无法刷新视图

// 嵌套类型
class Person{
   name:string
   age:number
   friend:Person

  constructor(name:string,age:number,friend?:Person) {
    this.name=name
    this.age=age
    this.friend=friend
  }
}

@Entry
@Component
struct Index {
  @State xiaoming: Person = new Person('xiaoming',13)
  @State xiaohong: Person = new Person('xiaohong',14,new Person("lilei",14))

  build() {
    Row() {
      Column() {
        Text(this.xiaoming.name+"的年龄"+this.xiaoming.age)
          .fontSize(20)
          .fontWeight(FontWeight.Bold)
          .onClick(()=>{
            // 会刷新ui
            this.xiaoming.age++
          })

        Text(this.xiaohong.name+"的朋友的年龄"+this.xiaohong.friend.age)
          .fontSize(20)
          .fontWeight(FontWeight.Bold)
          .onClick(()=>{
            // 嵌套类型,不会刷新ui
            this.xiaohong.friend.age++
          })
      }
      .width('100%')
    }
    .height('100%')
  }
}

数组中的对象属性无法触发视图更新

class Person {
  name: string
  age: number
  friend: Person

  constructor(name: string, age: number, friend?: Person) {
    this.name = name
    this.age = age
    this.friend = friend
  }
}

@Entry
@Component
struct Index {
  @State xiaoming: Person = new Person('xiaoming', 13)
  @State friendList: Person[] = [
    new Person("lilei", 14),
    new Person("lilei2", 15)
  ]

  build() {
    Row() {
      Column() {
        Text("朋友列表")
          .fontSize(40)
          .fontWeight(FontWeight.Bold)
        Button("添加朋友")
          .onClick(() => {
            // 点击会增加
            let friendIndex = this.friendList.length
            this.friendList.push(new Person("lilei" + friendIndex, 20))
          })
        ForEach(this.friendList, (item, index) => {
          Row({space:10}) {
            Text(item.name + "的年龄" + item.age)
              .fontSize(20)
              .fontWeight(FontWeight.Bold)
              .onClick(() => {
                // 点击不会发生年龄变更
                item.age++
              })
            Button("删除朋友")
              .onClick(() => {
                // 点击会删除当前项
                this.friendList.splice(index, 1)
              })
          }.width('100%').justifyContent(FlexAlign.SpaceAround)
          .margin({bottom:10,left:10,right:10})
          .borderRadius(15)
          .padding(10)
          .backgroundColor('#cccccc')

        })

      }
      .width('100%')
      .height('100%')
      .justifyContent(FlexAlign.Start)
    }
    .height('100%')
  }
}

应用示例

在这里插入图片描述

涉及内容:
基础组件:Progress CheckBox
容器组件:Stack List

class Task {
  static id: number = 1
  name: string = '任务' + Task.id++
  isDone: boolean = false
}

@Extend(Text) function finishedTask() {
  .decoration({ type: TextDecorationType.LineThrough })
  .fontColor('#B1B2B1')
}

@Entry
@Component
struct TaskPage {
  // 总任务数量
  @State totalTask: number = 0
  @State finishTask: number = 0
  @State taskList: Array<Task> = []

  build() {
    Column() {
      // 1.顶部任务统计部分
      this.TaskProgressView()
      // 2.新增任务
      Button("新增任务").onClick(() => {
        this.taskList.push(new Task())
        this.totalTask = this.taskList.length
      }).width("60%")
        .margin({ top: 10 })
      // 3.任务列表
      List() {
        ForEach(this.taskList, (item, index) => {
          ListItem() {
            this.TaskItemView(item)
          }.swipeAction({ end: this.getDeleteButton(index) })// 向左滑动,出现删除按钮
        })
      }.layoutWeight(1) // 高度权重
      .width('100%')
      .alignListItem(ListItemAlign.Center)
    }
    .width('100%')
    .height('100%')
    .backgroundColor('#eeeeee')
    .justifyContent(FlexAlign.Start)
  }

  @Builder TaskProgressView() {
    Row() {
      Text("任务进度:")
        .fontSize(20)
        .fontWeight(FontWeight.Bold)
        .margin({ right: 40 })
      Stack() {
        Progress({ value: this.finishTask, type: ProgressType.Ring, total: this.totalTask }).width(120)
        Text(this.finishTask + "/" + this.totalTask)
          .fontSize(20)
          .fontWeight(FontWeight.Bold)
      }
    }.commonCardStyle()
    .height(200)
    .padding({ left: 20, right: 20 })
    .justifyContent(FlexAlign.Center)
  }

  @Builder TaskItemView(task: Task) {
    Row() {
      // 这里不生效,原因:state 数组对象嵌套不刷新视图
      if (task.isDone) {
        Text(task.name)
          .fontSize(15)
          .fontWeight(FontWeight.Bold)
          .margin({ right: 40 })
          .finishedTask()
      } else {
        Text(task.name)
          .fontSize(15)
          .fontWeight(FontWeight.Bold)
          .margin({ right: 40 })
      }
      Checkbox()
        .select(task.isDone).onChange((isChecked) => {
        task.isDone = isChecked
        this.finishTask = this.taskList.filter(item => item.isDone).length
      })
    }.commonCardStyle()
    .height(100)
    .padding({ left: 20, right: 20 })
    .justifyContent(FlexAlign.SpaceBetween)
  }

  @Builder getDeleteButton(index: number) {
    Button({ type: ButtonType.Circle }) {
      Image($r('app.media.del'))
    }
    .onClick(() => {
      this.taskList.splice(index, 1)
      this.finishTask = this.taskList.filter(item => item.isDone).length
      this.totalTask = this.taskList.length
    })
    .width(50)
    .height(50)
    .padding(10)
    .margin({ right: 5 })
    .backgroundColor('#ffffff')
  }

  @Styles commonCardStyle(){
    .width('95%')
    .margin({ left: 10, right: 10, top: 10 })
    .borderRadius(20)
    .backgroundColor('#ffffff')
    .shadow({ radius: 6, color: '#1f000000', offsetX: 2, offsetY: 4 })
  }
}

@Prop 和 @Link

@Provide和 @Consume

@Observerd 和 ObjectLink


http://lihuaxi.xjx100.cn/news/1920446.html

相关文章

MIT线性代数笔记-第31讲-线性变换及对应矩阵

目录 31.线性变换及对应矩阵打赏 31.线性变换及对应矩阵 线性变换相当于是矩阵的抽象表示&#xff0c;每个线性变换都对应着一个矩阵 例&#xff1a; 考虑一个变换 T T T&#xff0c;使得平面上的一个向量投影为平面上的另一个向量&#xff0c;即 T : R 2 → R 2 T:R^2 \to R…

腾讯云轻量应用服务器购买流程(两种方式)

腾讯云轻量应用服务器购买指南&#xff0c;有两个入口&#xff0c;一个是在特价活动上购买&#xff0c;一个是在轻量应用服务器官方页面购买&#xff0c;特价活动上购买价格更便宜&#xff0c;轻量2核2G3M带宽服务器62元一年起&#xff0c;阿腾云atengyun.com分享腾讯云轻量应用…

成考生必看!2023年成人高考录取后入学拿证流程

成人高考录取后并不是就可以坐等拿证了&#xff01; 成人高考录取后你还有这些事情要做。 一起来了解一下吧&#xff01; 成人高考入学到拿证流程 办理入学流程 1.入学时间 确认被高校录取后&#xff0c;12月下旬左右开始办理入学(实际时间以各院校安排为准&#xff09; 2.缴…

DDP分布式训练的官方demo及相关知识

参考链接 1.分布式训练&#xff1a;并行化&#xff0c;跨进程和跨集群的计算 2.torch.distributed.init_process_group() 来初始化进程组,需要指定worker的通信机制,一般为nccl(NVIDIA推出)&#xff0c;1个进程对应1个gpu.nccl是nvidia的显卡通信方式&#xff0c;用于把模型参数…

ts中的任意接口

interface Persontest {name:string;[key:string]:any } var psss:Persontest{name:1,age:10,sex:男,[Symbol()]:灵境胡同 }ts中&#xff0c;[Symbol()] 是一个计算属性名称的语法&#xff0c;可以在对象字面量中使用 Symbol 类型来动态地生成属性名称&#xff0c;[Symbol()] 生…

react 代数效应 和 vue vm思想

前言 React 的代数效应和 Vue 的 VM 思想是两种不同的编程模型&#xff0c;它们都试图解决 UI 开发中的一些挑战&#xff0c;如副作用管理、状态同步、组件抽象等。 React 的代数效应 是指将副作用从函数调用中分离&#xff0c;使函数关注点保持纯粹&#xff0c;同时通过代数运…

ChatGPT4助力Python数据分析与可视化、人工智能建模及论文高效撰写

2022年11月30日&#xff0c;可能将成为一个改变人类历史的日子——美国人工智能开发机构OpenAI推出了聊天机器人ChatGPT3.5&#xff0c;将人工智能的发展推向了一个新的高度。2023年4月&#xff0c;更强版本的ChatGPT4.0上线&#xff0c;文本、语音、图像等多模态交互方式使其在…

centos 编译安装 libxml-2.0

centos 编译安装 libxml-2.0 下载地址 我下载的 libxml2-2.9.12.tar.gz 版本 下载后解压&#xff0c;进入解压后的目录 执行&#xff1a; ./configure make && make install安装过程中出现 <Pyghon.h> 找不到的问题&#xff0c;指定了路径之后还是找不到&…