【鸿蒙学习笔记】@Prop装饰器:父子单向同步

news2024/7/6 20:00:52

官方文档:@Prop装饰器:父子单向同步

[Q&A] @Prop装饰器作用

@Prop装饰的变量可以和父组件建立单向的同步关系。@Prop装饰的变量是可变的,但是变化不会同步回其父组件。

[Q&A] @Prop装饰器特点

1・@Prop装饰器不能在@Entry装饰的自定义组件中使用。
2・@Prop装饰变量时会进行深拷贝,在拷贝的过程中除了基本类型、Map、Set、Date、Array外,都会丢失类型。

样例1:Date

@Component
struct DateComponent {
  @Prop childSelectedDate: Date = new Date('');

  build() {
    Column() {
      Row() {
        Button('child +1年').margin(5).width('30%')
          .onClick(() => {
            this.childSelectedDate.setFullYear(this.childSelectedDate.getFullYear() + 1)
          })
        Button('child +1月').margin(5).width('30%')
          .onClick(() => {
            this.childSelectedDate.setMonth(this.childSelectedDate.getMonth() + 1)
          })
        Button('child +1天').margin(5).width('30%')
          .onClick(() => {
            this.childSelectedDate.setDate(this.childSelectedDate.getDate() + 1)
          })
      }.width('100%')

      Button('child 重置日期').margin(10).width('100%')
        .onClick(() => {
          this.childSelectedDate = new Date('2023-07-07')
        })

      DatePicker({
        start: new Date('1970-1-1'),
        end: new Date('2100-1-1'),
        selected: this.childSelectedDate
      })
    }
  }
}

@Entry
@Component
struct SizeExample {
  @State parentSelectedDate: Date = new Date('2008-08-08');

  build() {
    Column() {
      Row() {
        Button('parent +1年').margin(5).width('30%')
          .onClick(() => {
            this.parentSelectedDate.setFullYear(this.parentSelectedDate.getFullYear() + 1)
          })
        Button('parent +1月').margin(5).width('30%')
          .onClick(() => {
            this.parentSelectedDate.setMonth(this.parentSelectedDate.getMonth() + 1)
          })
        Button('parent +1天').margin(5).width('30%')
          .onClick(() => {
            this.parentSelectedDate.setDate(this.parentSelectedDate.getDate() + 1)
          })
      }.width('100%')

      Button('parent 重置日期').margin(10).width('100%')
        .onClick(() => {
          this.parentSelectedDate = new Date('2023-07-07')
        })

      DatePicker({
        start: new Date('1970-1-1'),
        end: new Date('2100-1-1'),
        selected: this.parentSelectedDate
      })
      DateComponent({ childSelectedDate: this.parentSelectedDate })
    }
  }
}

在这里插入图片描述

样例2:父组件@State简单数据类型→子组件@Prop简单数据类型同步

@Component
struct CountDownComponent {
  @Prop count: number = 0;
  costOfOneAttempt: number = 1;

  build() {
    Row() {
      if (this.count > 0) {
        Text(`当前值为 ${this.count} .`).fontSize(20).margin(10).textAlign(TextAlign.Center)
      } else {
        Text('Game over!').fontSize(20).margin(10)
      }
      Button('子 -1').onClick(() => {
        this.count -= this.costOfOneAttempt;
      }).width("40%")
    }.width('100%')
  }
}

@Entry
@Component
struct SizeExample {
  @State countDownStartValue: number = 10;

  build() {
    Column() {
      Row() {
        if (this.countDownStartValue > 0) {
          Text(`当前值为 ${this.countDownStartValue} .`).fontSize(20).margin(5).textAlign(TextAlign.Center)
        } else {
          Text('Game over!').fontSize(20).margin(10)
        }

        Button('父 +1 ').onClick(() => {
          this.countDownStartValue += 1;
        }).margin(5).width("20%")

        Button('父 -1 ').onClick(() => {
          this.countDownStartValue -= 1;
        }).margin(5).width("20%")
      }.width('100%')

      CountDownComponent({ count: this.countDownStartValue, costOfOneAttempt: 2 })
    }
  }
}

在这里插入图片描述

样例3:父组件@State数组项→子组件@Prop简单数据类型同步

@Component
struct Child {
  @Prop value: number = 0;

  build() {
    Text(`${this.value}`).fontSize(30)
      .onClick(() => {
        this.value++
      })
  }
}

@Entry
@Component
struct SizeExample {
  @State arr: number[] = [1, 2, 3];

  build() {
    Row() {

      Column() {
        Text(`当前值为 ${this.arr[0]},${this.arr[1]},${this.arr[2]}.`).fontSize(30).margin(10).textAlign(TextAlign.Center)

        Divider().height(10)

        Row() {
          Child({ value: this.arr[0] }).width('30%').align(Alignment.Center).backgroundColor(Color.Red)
          Child({ value: this.arr[1] }).width('30%').align(Alignment.Center).backgroundColor(Color.Green)
          Child({ value: this.arr[2] }).width('30%').align(Alignment.Center).backgroundColor(Color.Yellow)
        }.alignItems(VerticalAlign.Center)

        Divider().height(10)

        Row() {
          ForEach(this.arr, (item: number) => {
            Child({ value: item }).width('30%').align(Alignment.Center).backgroundColor(Color.Orange).border({ width: 1, style: BorderStyle.Dashed })
          }, (item: string) => item.toString())
        }.alignItems(VerticalAlign.Center)

        Divider().height(10)

        Text('重置').fontSize(30).backgroundColor(Color.Pink).width('50%').textAlign(TextAlign.Center).padding(10)
          .onClick(() => {
            // 两个数组都包含项“3”。
            this.arr = this.arr[0] == 1 ? [3, 4, 5] : [1, 2, 3];
          })
      }
    }
  }
}

在这里插入图片描述

样例4:父组件@State类对象属性→@Prop简单类型的同步

class Book {
  public title: string;
  public pages: number;
  public readIt: boolean = false;

  constructor(title: string, pages: number) {
    this.title = title;
    this.pages = pages;
  }
}

@Component
struct ReaderComp {
  @Prop book: Book = new Book("", 0);

  build() {
    Row() {
      Text(this.book.title).fontSize(20)
      Text(` 有 ${this.book.pages}! `).fontSize(20)
      Text(`${this.book.readIt ? " 我读了" : ' 我还没开始读'}`).fontSize(20)
        .onClick(() => this.book.readIt = true).backgroundColor(Color.Pink)
    }
  }
}

@Entry
@Component
struct SizeExample {
  @State book: Book = new Book('资治通鉴', 765);

  build() {
    Column() {
      ReaderComp({ book: this.book })
      ReaderComp({ book: this.book })
    }
  }
}

在这里插入图片描述

样例5:父组件@State数组项→@Prop class类型的同步

let nextId: number = 1;

@Observed // @Prop在子组件装饰的状态变量和父组件的数据源是单向同步关系,需要使用@Observed装饰class Book,Book的属性将被观察。
class Book {
  public id: number;
  public title: string;
  public pages: number;
  public readIt: boolean = false;

  constructor(title: string, pages: number) {
    this.id = nextId++;
    this.title = title;
    this.pages = pages;
  }
}

@Component
struct ReaderComp {
  @Prop book: Book = new Book("", 1);

  build() {
    Row() {
      Text(` ${this.book ? this.book.title : "未定义"}`).fontColor(Color.Red)
      Text(` 有 ${this.book ? this.book.pages : "未定义"}!`).fontColor(Color.Black)
      Text(` ${this.book ? (this.book.readIt ? "我已经读了" : '我还没读' ): "未定义"}`).fontColor(Color.Blue)
        .onClick(() => this.book.readIt = true)
    }
  }
}

@Entry
@Component
struct SizeExample {
  @State allBooks: Book[] = [new Book("资治通鉴", 100), new Book("史记", 100), new Book("论语", 100)];

  build() {
    Column() {
      Text('畅销书').width(312).height(40).fontSize(20).margin(12).fontColor('#e6000000')
      ReaderComp({ book: this.allBooks[2] }).backgroundColor('#0d000000').width(312).height(40).padding({ left: 20, top: 10 }).borderRadius(20).colorBlend('#e6000000')

      Divider()

      Text('已经购买的书').width(312).height(40).fontSize(20).margin(12).fontColor('#e6000000')
      ForEach(this.allBooks, (book: Book) => {
        ReaderComp({ book: book }).margin(12).width(312).height(40).padding({ left: 20, top: 10 }).backgroundColor('#0d000000').borderRadius(20)
      },(book: Book) => book.id.toString())

      Button('追加').width(312).height(40).margin(12).fontColor('#FFFFFF 90%')
        .onClick(() => {
          this.allBooks.push(new Book("孟子", 100));
        })

      Button('移除第一本书').width(312).height(40).margin(12).fontColor('#FFFFFF 90%')
        .onClick(() => {
          if (this.allBooks.length > 0){
            this.allBooks.shift();
          } else {
            console.log("length <= 0")
          }
        })

      Button("所有人都已经读了").width(312).height(40).margin(12).fontColor('#FFFFFF 90%')
        .onClick(() => {
          this.allBooks.forEach((book) => book.readIt = true)
        })
    }
  }
}

在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1891122.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

关于ant design vue 使用Modal无法关闭弹窗的解决思路

文章目录 1: 出现问题的版本2.出现问题&#xff08;1&#xff09;ant design 的问题&#xff08;2&#xff09;poina的提示报错 3.正确版本总结 1: 出现问题的版本 "ant-design-vue": "^3.2.20", "pinia": "^2.1.7", "vue"…

Mybatis Plus 自动填充注解 @TableField(fill = FieldFill.INSERT_UPDATE)

第一步&#xff1a;在需要自动填充的位置加上注解 通过在创建时间和修改时间上添加 fill 填充字段 进行自动填充 第二步&#xff1a;要想实现自动填充还需要实现MetaObjectHandler接口&#xff0c;在这里实现自动填充的逻辑 Component public class MyMetaObjectHandler …

python sklearn机械学习-数据预处理

&#x1f308;所属专栏&#xff1a;【机械学习】✨作者主页&#xff1a; Mr.Zwq✔️个人简介&#xff1a;一个正在努力学技术的Python领域创作者&#xff0c;擅长爬虫&#xff0c;逆向&#xff0c;全栈方向&#xff0c;专注基础和实战分享&#xff0c;欢迎咨询&#xff01; 您…

filex文件系统功能预研

filex资源 filex的源码路径有两个&#xff1a; 一个是azure-rtos下的filex&#xff1a;azure-rtos/filex (github.com)一个是eclipse-threadx下的filex&#xff1a;eclipse-threadx/filex filex的文档地址&#xff1a;rtos-docs/rtos-docs/filex 第三方文档&#xff1a;Thre…

搭建知识付费系统的技术框架与实现路径

知识付费系统已经成为内容创作者和企业变现的重要工具。要成功搭建一个高效、稳定、用户体验良好的知识付费系统&#xff0c;明确技术框架和实现路径至关重要。本文将详细解析搭建知识付费系统的技术框架&#xff0c;并提供具体的实现路径和相关技术代码示例。 一、知识付费系…

大陆ARS548使用记录

一、Windows连接上位机 雷达是在深圳路达买的&#xff0c;商家给的资料中首先让配置网口&#xff0c;但我在使用过程中一直出现无法连接上位机的情况。接下来说说我的见解和理解。 1.1遇到的问题 按要求配置好端口后上位机无连接不到雷达&#xff0c;但wireshark可以正常抓到数…

基于改进YOLOv5s的跌倒行为检测 | 引入SKAttention注意机制 + 引入空间金字塔池化结构SPPFCSPC + 结合ASFF自适应空间融合

前言&#xff1a;Hello大家好&#xff0c;我是小哥谈。为了实现电厂人员跌倒行为的实时检测&#xff0c;防止跌倒昏迷而无法及时发现并救援的事件发生&#xff0c;针对跌倒行为检测实时性以及特征提取能力不足的问题&#xff0c;提出了一种改进YOLOv5s的跌倒行为检测算法网络&a…

公网IP变更自动微信通知与远程执行命令的C++开源软件

基本功能 智能公网IP变更监测与微信通知 一旦检测到公网IP地址发生变更&#xff0c;系统将自动通过预设的QQ邮箱&#xff08;该邮箱与微信绑定&#xff0c;实现微信通知&#xff09;发送新IP地址通知。同时&#xff0c;软件会即时更新本地配置文件中的IP地址及变更时间&#…

MySQL Server使用

MySQL Server MySQL Server基本操作查看数据库服务命令行连接&#xff08;这些操作都可以在workbench中进行&#xff09; MySQL Server基本操作 MySQL基础&#xff1a;安装卸载与配置 查看数据库服务 电脑–管理–管理和应用程序–服务–MySQL80 命令行连接&#xff08;这…

Linux线程:编织并发的梦幻世界

目录 &#x1f6a9;引言 &#x1f6a9;听故事&#xff0c;引概念 &#x1f6a9;生产者消费者模型 &#x1f680;再次理解生产消费模型 &#x1f680;挖掘特点 &#x1f6a9;条件变量 &#x1f680;条件变量常用接口 &#x1f680;条件变量的原理 &#x1f6a9;引言 上一篇…

HQChart报价列表高级应用教程7-走势列数据对接

HQChart报价列表高级应用教程7-走势列数据对接 走势列小程序效果图PC效果图HQChart代码地址走势列类型配置走势列数据格式示例走势列 单独使用一列显示每个股票的走势图 小程序效果图 PC效果图 HQChart代码地址 地址:github.com/jones2000/HQChart

医院挂号系统:基于JSP和MySQL的现代化医疗预约平台

开头语&#xff1a;您好&#xff0c;我是专注于医疗系统开发的IT学长。如果您对医院挂号系统感兴趣&#xff0c;欢迎联系我。 开发语言&#xff1a;Java 数据库&#xff1a;MySQL 技术&#xff1a;JSP技术&#xff0c;B/S架构 工具&#xff1a;Eclipse&#xff0c;MyEclips…

大模型对汽车行业意味着什么?_汽车企业大模型

引 言 大模型是一种利用海量数据进行训练的深度神经网络模型&#xff0c;其特点是拥有庞大的参数规模和复杂的计算结构。通过在大规模数据集上进行训练&#xff0c;大模型能够学习到丰富的模式和特征&#xff0c;从而具备强大的泛化能力&#xff0c;可以对未知数据做出准确的预…

10 - matlab m_map地学绘图工具基础函数 - 绘制多边形区域、流线图、散点图和添加注释的有关函数

10 - matlab m_map地学绘图工具基础函数 - 绘制多边形区域、流线图、散点图和添加注释的有关函数 0. 引言1. 关于m_patch2. 关于m_streamline3. 关于m_scatter4. 关于m_annotation5. 结语 0. 引言 本篇介绍下m_map中绘制多边形区域函数&#xff08;m_patch&#xff09;、绘制流…

Landsat数据从Collection1更改为Collection2

目录 问题解决 问题 需要注意!您使用的是废弃的陆地卫星数据集。为确保功能持续&#xff0c;请在2024年7月1日前更新。 在使用一些以前的代码时会遇到报错&#xff0c;因为代码里面用的是老的数据集 解决 对于地表反射率SR&#xff0c;需要在name中&#xff0c;将C01换为C02&…

Mysql-基础-DDL操作

1、数据库操作 查询 查询所有数据库 show databases; 创建 创建数据库 create database [if not exists] 数据库名 使用及查询 use 数据库名 select database() 查询当前所处数据库 删除 drop database [if not exists] 数据库名 2、表操作 查询当前库中的所…

SpringBoot源码阅读3-启动原理

SpringBootApplication public class DistApplication {public static void main(String[] args) {// 启动入口SpringApplication.run()SpringApplication.run(DistApplication.class, args);} }1、服务构建 这里"服务"指的是SpringApplication对象&#xff0c;服务…

安防视频监控/视频汇聚EasyCVR平台国标GB28181级联上级平台,视频无法播放是什么原因?

安防视频监控/视频集中存储/云存储/磁盘阵列EasyCVR平台可拓展性强、视频能力灵活、部署轻快&#xff0c;EasyCVR基于云边端一体化架构&#xff0c;具有强大的数据接入、处理及分发能力&#xff0c;可提供7*24小时实时高清视频监控、云端录像、云存储、录像检索与回看、智能告警…

24位DAC转换的FPGA设计及将其封装成自定义IP核的方法

在vivado设计中,为了方便的使用Block Desgin进行设计,可以使用vivado软件把自己编写的代码封装成IP核,封装后的IP核和原来的代码具有相同的功能。本文以实现24位DA转换(含并串转换,使用的数模转换器为CL4660)为例,介绍VIVADO封装IP核的方法及调用方法,以及DAC转换的详细…

【postgreessql 】统计库中的所有表数量

在PostgreSQL中&#xff0c;你可以使用SQL查询来统计数据库中的所有表数量。这通常涉及到查询系统目录表&#xff0c;特别是 pg_catalog.pg_tables 表&#xff0c;它存储了关于数据库中所有表的信息。 SELECT COUNT(*) FROM information_schema.tables WHERE table_schema IN …