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

官方文档:@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)})}}
}

在这里插入图片描述

样例6:@Prop本地初始化不和父组件同步

@Component
struct MyComponent {@Prop count1: number;@Prop count2: number = 5;build() {Column() {Row() {Text(`Parent: ${this.count1}`).fontColor('#ff6b6565').width('30%')Text(`Child: ${this.count2}`).fontColor('#ff6b6565').width('30%')Button('改变Child数值').width('30%').height(40).fontColor('#FFFFFF,90%').onClick(() => {this.count2++})}}}
}@Entry
@Component
struct SizeExample {@State mainCount: number = 10;build() {Column() {Row() {Column() {MyComponent({ count1: this.mainCount })Divider().height(10)MyComponent({ count1: this.mainCount, count2: this.mainCount })}}Divider().height(10)Column() {Button('改变Parent数值').width(288).height(40).width('100%').fontColor('#FFFFFF,90%').onClick(() => {this.mainCount++})}}}
}

在这里插入图片描述

样例7:@Prop嵌套场景

几个按钮跳的乱,需要消化

@Entry
@Component
struct SizeExample {@State book: Book = new Book('Book名字', new Title('Book标题'))build() {Column() {Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) {Text(this.book.name).fontSize(16).margin(12).width(312).height(40).backgroundColor(Color.Green).borderRadius(20).textAlign(TextAlign.Center).fontColor('#e6000000').onClick(() => {this.book.name = '资治通鉴'})Text(this.book.title.title).fontSize(16).margin(12).width(312).height(40).backgroundColor(Color.Green).borderRadius(20).textAlign(TextAlign.Center).onClick(() => {this.book.title.title = "资治通鉴 标题"})ShowTitle({ title: this.book.title })Button('修改 Book 名字').width(312).height(40).margin(12).fontColor('#FFFFFF,90%').onClick(() => {this.book.name = "史记"})Button('修改 Book 标题').width(312).height(40).margin(12).fontColor('#FFFFFF,90%').onClick(() => {this.book.title.title = "史记 标题"})}}}
}@Component
struct ShowTitle {@Prop title: Title = new Title('');build() {Column() {Text(this.title.title).fontSize(16).margin(12).width(312).height(40).backgroundColor(Color.Orange).borderRadius(20).textAlign(TextAlign.Center).onClick(() => {this.title.title = '点击完毕'})}}
}// 以下是嵌套类对象的数据结构。
@Observed
class Title {public title: string;constructor(title: string) {this.title = title;}
}@Observed
class Book {public name: string;public title: Title;constructor(name: string, cla: Title) {this.name = name;this.title = cla;}
}

在这里插入图片描述

样例8:装饰Map类型变量

@Component
struct MapComponent {@Prop map: Map<number, string> = new Map([[0, "a"], [1, "b"], [3, "c"]])build() {Column() {ForEach(Array.from(this.map.entries()), (item: [number, string]) => {Row(){Text(`${item[0]}`).fontSize(30).margin(10)Text(`${item[1]}`).fontSize(30).margin(10)}Divider()})Button('初始化').margin(5).width('100%').onClick(() => {this.map = new Map([[0, "a"], [1, "b"], [3, "c"]])})Button('追加1组值').margin(5).width('100%').onClick(() => {this.map.set(4, "d")})Button('清除所有值').margin(5).width('100%').onClick(() => {this.map.clear()})Button('替换第1个值').margin(5).width('100%').onClick(() => {this.map.set(0, "aa")})Button('删除第1个值').margin(5).width('100%').onClick(() => {this.map.delete(0)})}}
}@Entry
@Component
struct SizeExample {@State message: Map<number, string> = new Map([[1, "a"], [2, "b"], [3, "c"]])build() {Row() {Column() {MapComponent({ map: this.message })}.width('100%').backgroundColor(Color.Green)}.height('100%').backgroundColor(Color.Pink)}
}

在这里插入图片描述

样例9:装饰Set类型变量

@Component
struct Child {@Prop message: Set<number> = new Set([0, 1, 2, 3, 4])build() {Column() {Row() {ForEach(Array.from(this.message.entries()), (item: [number, string]) => {Text(`${item[0]}`).fontSize(30).margin(10)})}Button('初始化Set').width('100%').onClick(() => {this.message = new Set([0, 1, 2, 3, 4])})Divider().height(10)Button('追加新值').width('100%').onClick(() => {this.message.add(5)})Divider().height(10)Button('清除所有值').width('100%').onClick(() => {this.message.clear()})Divider().height(10)Button('删除第一个值').width('100%').onClick(() => {this.message.delete(0)})}.width('100%')}
}@Entry
@Component
struct SizeExample {@State message: Set<number> = new Set([0, 1, 2, 3, 4])build() {Row() {Column() {Child({ message: this.message })}.width('100%')}.height('100%')}
}

在这里插入图片描述

样例10:Prop支持联合类型实例

class Animals {public name: string;constructor(name: string) {this.name = name;}
}@Component
struct Child {@Prop animal: Animals | undefined;build() {Column() {Text(`子  ${this.animal instanceof Animals ? this.animal.name : '未定义'}`).fontSize(20).backgroundColor(Color.Pink).width('100%').padding(5)Button('子 改为猫').width('100%').margin(5).onClick(() => {// 赋值为Animals的实例this.animal = new Animals("猫")})Button('子 改为 undefined').width('100%').margin(5).onClick(() => {// 赋值为undefinedthis.animal = undefined})}.width('100%')}
}@Entry
@Component
struct SizeExample {@State animal: Animals | undefined = new Animals("老虎");build() {Column() {Text(`父  ${this.animal instanceof Animals ? this.animal.name : '未定义'}`).fontSize(20).textAlign(TextAlign.Start).backgroundColor(Color.Yellow).width('100%').padding(5)Child({ animal: this.animal })Button('父 改为狗').width('100%').margin(5).onClick(() => {if (this.animal instanceof Animals) {this.animal.name = "狗"} else {console.info('num is undefined, cannot change property')}})Button('父 改为 undefined').width('100%').margin(5).onClick(() => {this.animal = undefined})}.backgroundColor(Color.Orange)}
}

在这里插入图片描述

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

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

相关文章

MySQL数据库增删改查示例

一、 1、登陆数据库 2、创建数据库zoo 3、修改数据库zoo字符集为gbk 4、选择当前数据库为zoo 5、查看创建数据库zoo信息 6、删除数据库zoo 二、创建俩张表 先创建一个数据库并使用&#xff1a; 创建员工表 创建员工绩效表 三、修改表 1.在员工表的基本上增加一个image系列&a…

设计模型 - 学习笔记

学习参考&#xff1a; https://blog.csdn.net/m0_65346405/article/details/136994128 《系统分析师教程》 《设计模式之禅》 一. 设计模式的5大原则 1. 单一职责原则 一个类应该只有一个变化因子。 就是说&#xff0c;一个类要变化&#xff0c;比如增加功能&#xff0c;那么引…

C语言 | Leetcode C语言题解之第205题同构字符串

题目&#xff1a; 题解&#xff1a; struct HashTable {char key;char val;UT_hash_handle hh; };bool isIsomorphic(char* s, char* t) {struct HashTable* s2t NULL;struct HashTable* t2s NULL;int len strlen(s);for (int i 0; i < len; i) {char x s[i], y t[i]…

盘点一波国际上最具挑战性的11个IT认证,你有几个证书?

在信息技术领域&#xff0c;获得认证不仅是对专业知识和技能的认可&#xff0c;更是提升职业竞争力的重要手段。 随着技术的发展和行业的需求&#xff0c;IT认证的种类越来越多&#xff0c;难度也越来越大。 你可能听说过一些知名的认证&#xff0c;比如思科的CCIE、华为的HCIE…

自闭症儿童:探索症状背后的多彩内心世界

在星启帆自闭症康复中心&#xff0c;我们每天与一群独特而珍贵的孩子相遇——他们&#xff0c;是自闭症谱系障碍的患儿。自闭症&#xff0c;这一复杂的神经发育障碍&#xff0c;以其多样化的症状表现&#xff0c;为每个孩子的生活轨迹绘上了不同的色彩。 自闭症孩子的症状各异…

springboot的非物质文化遗产管理系统-计算机毕业设计源码16087

目录 摘要 1 绪论 1.1 选题背景与意义 1.2国内外研究现状 1.3论文结构与章节安排 2系统分析 2.1 可行性分析 2.2 系统流程分析 2.2.1系统开发流程 2.2.2 用户登录流程 2.2.3 系统操作流程 2.2.4 添加信息流程 2.2.5 修改信息流程 2.2.6 删除信息流程 2.3 系统功能…

微信小程序 typescript 开发日历界面

1.界面代码 <view class"o-calendar"><view class"o-calendar-container" ><view class"o-calendar-titlebar"><view class"o-left_arrow" bind:tap"prevMonth">《</view>{{year}}年{{month…

Maven:下载配置教学(2024版 最简)

文章目录 一、Maven下载1.1 下载官网1.2 下载压缩包1.3 解压1.4 创建repo文件夹 二、Maven配置2.1 环境变量2.1.1 新建系统变量2.1.2 添加Path 2.2 阿里云镜像2.3 JDK2.4 本地仓库2.5 conf文件的全部内容2.6 测试安装配置是否成功 三、IDEA中配置Maven3.1 新配置3.2 推荐配置 四…

在Clion使用CubeMX Stm32的步骤

Step1 准备软件&#xff0c;安装环境&#xff1a; 1. cubemx v6.5.0&#xff08;可以兼容以前版本的project&#xff09; https://www.st.com.cn/zh/development-tools/stm32cubemx.html STM32CubeMX 默认安装目录, 6.5版本可以兼容老版本 C:\Program Files\STMicroelectroni…

Redis数据迁移-RedisShake

redis-shake是阿里云Redis团队开源的用于Redis数据迁移和数据过滤的工具。 一、基本功能 redis-shake它支持解析、恢复、备份、同步四个功能 恢复restore&#xff1a;将RDB文件恢复到目的redis数据库。 备份dump&#xff1a;将源redis的全量数据通过RDB文件备份起来。 解析deco…

CM311-5_系列通用_gk6323_安卓9_U盘卡刷短接强刷固件(带教程)

魔百和CM311-5_系列通用_gk6323V100C_安卓9_优盘卡刷短接强刷固件包&#xff08;带教程&#xff09;&#xff0c;可以解决开ADB刷机方法 进不去rec的问题。 CM311-5系列的盒子都能用&#xff0c;下面CM311-5 这个系列的强刷固件和教程分享给大家&#xff0c;进不去rec的兄弟们…

一分钟教你设置代理服务器的IP地址

许多人购买完代理IP却不会使用&#xff0c;我们来学习一下如何手把手地设置代理服务器的IP地址。无论是为了访问受限网站还是保护隐私&#xff0c;设置代理IP都是一个非常实用的技能。让我们一起来看看怎么做吧&#xff01; 设置代理服务器的IP地址步骤 1. 选择代理服务提供商…

《安全大模型技术与市场研究报告》发布,海云安榜上有名

近日&#xff0c;网络安全产业研究机构“数说安全”发布2024《安全大模型技术与市场研究报告》&#xff08;以下简称“报告”&#xff09;。 海云安凭借在开发安全领域的优秀业务能力以及在大模型相关技术研究方面的成就得到了认可&#xff0c;入选“安全开发大模型推荐供应商”…

高效使用 Guzzle:POST 请求与请求体参数的最佳实践

介绍 在现代爬虫技术中&#xff0c;高效发送 HTTP 请求并处理响应数据是关键步骤之一。Guzzle 是一个强大的 PHP HTTP 客户端&#xff0c;广泛应用于发送同步和异步请求。本文将介绍如何使用 Guzzle 发送 POST 请求&#xff0c;特别是如何传递请求体参数&#xff0c;并结合代理…

【Python】Python的安装与环境搭建

个人主页&#xff1a;【&#x1f60a;个人主页】 系列专栏&#xff1a;【❤️Python】 文章目录 前言Python下载环境配置测试环境变量是否配置成功配置环境变量 运行Python交互式解释器&#xff1a;命令行脚本集成开发环境&#xff08;IDE&#xff1a;Integrated Development E…

检测水管缺水的好帮手-管道光电液位传感器

管道光电液位传感器是现代清水管道管理中的重要技术创新&#xff0c;不仅提高了检测液位的精确度&#xff0c;还解决了传统机械式和电容式传感器存在的诸多问题&#xff0c;成为检测管道缺水的可靠利器。 该传感器采用先进的光学感应原理&#xff0c;利用红外光学组件通过精密…

【vite创建项目】

搭建vue3tsvitepinia框架 一、安装vite并创建项目1、用vite构建项目2、配置vite3、找不到模块 “path“ 或其相对应的类型声明。 二、安装element-plus1、安装element-plus2、引入框架 三、安装sass sass-loader1、安装sass 四、安装vue-router-next 路由1、安装vue-router42搭…

labview技巧——AMC框架安装

AMC工具包的核心概念是队列&#xff0c;队列是一种先进先出&#xff08;FIFO&#xff0c;First In First Out&#xff09;的数据结构&#xff0c;适用于处理并发和异步任务。在LabVIEW中&#xff0c;队列可以用于在不同VI之间传递数据&#xff0c;确保消息的有序处理&#xff0…

你觉得胡锡进还能回本吗?还能融资买纳指?

7月3日&#xff0c;胡锡进发布最新炒股日记&#xff1a;这几天的股票表现总体很差&#xff0c;除了今天&#xff0c;之前连续几天都输给了沪指&#xff0c;因此虽然今天我只赔了546元&#xff0c;但#胡锡进总亏损达到8.5万#。这是我今年一月份2800点以下时的亏损额。胡锡进称已…

如何快速选择短剧系统源码:高效构建您的在线短剧平台

在数字化时代&#xff0c;短剧作为一种新兴的娱乐形式&#xff0c;受到了广泛的欢迎。随着市场需求的增长&#xff0c;构建一个在线短剧平台成为了很多创业者和开发者的目标。而选择正确的短剧系统源码则是实现这一目标的关键步骤。本文将为您提供一些实用的指导&#xff0c;帮…