学习鸿蒙基础(8)

news/2024/4/28 2:23:11/文章来源:https://blog.csdn.net/huyawenz/article/details/137018711

一、@BuilderParam装饰器
当开发者创建了自定义组件,并想对该组件添加特定功能时,例如在自定义组件中添加一个点击跳转操作。若直接在组件内嵌入事件方法,将会导致所有引入该自定义组件的地方均增加了该功能。为解决此问题,ArkUI引入了@BuilderParam装饰器,@BuilderParam用来装饰指@Builder方法的变量,开发者可在初始化自定义组件时对此属性进行赋值,为自定义组件增加特定的功能。该装饰器用于声明任意UI描述的一个元素,类似slot占位符。

@Entry
@Component
struct Page_builderParam {@State message: string = 'Hello World'title: string = ''@State isShow: boolean = true;@Builderleft() {Row() {Button("大房子").onClick(()=>{this.isShow=!this.isShowconsole.log(this.isShow+"ddd")})}}@Builderright() {Row() {Button("好车子")}}@Builderlist1(){Column(){ForEach(["住宅","写字楼","商铺"],item=>{Text(item).fontColor(Color.Green).fontSize(19)})}}build() {Row() {Column() {Nav({ title: "金山", left: this.left.bind(this), right: this.right })if(this.isShow){list({list1:this.list1})}}.width('100%')}.height('100%')}
}@Component
struct Nav {title: string = ""@BuilderParam left: () => void@BuilderParam right: () => voidbuild() {Row() {this.left()Text(this.title)this.right()}.width("100%").justifyContent(FlexAlign.SpaceBetween)}
}@Component
struct list {title: string = ""@BuilderParam list1:()=>voidbuild() {Row() {this.list1()}.width("100%").height(89).margin({ top: 10 }).justifyContent(FlexAlign.SpaceBetween).backgroundColor(Color.Gray)}
}

二、生命周期

页面生命周期

即被@Entry装饰的组件生命周期。提供以下生命周期接口:
onPageShow: 页面每次显示时触发一次,包括路由过程、应用进入前台等场景,仅@Entry装饰的自定义组件生效。
onPageHide: 页面每次隐藏时触发一次,包括路由过程、应用进入前后台等场景,仅@Entry装饰的自定义组件生效。
onBackPress:当用户点击返回按时触发,仅@Entry装饰的自定义组件生效。
组件生命周期

即一般用@Component装饰的自定义组件的生命周期,提供以下生命周期接口:
aboutToAppear: 组件即将出现时回调该接口,具体时机为在创建自定义组件的新实例后,在执行其build()函数之前执行。
aboutToDisappear: 在自定义组件析构销毁之前执行。不允许在aboutToDisappear函数中改变状态变量,特别是@Link变量的修改可能会导致应用程序行为不稳定。

简单举例说明:

@Entry
@Component
struct PageLife {@State message: string = 'Hello World'@State isShow: boolean = true;// 页面准备-可以网络请求aboutToAppear() {console.log("aboutToAppear")}// 页面显示onPageShow() {console.log("onPageShow")}// 页面离开onPageHide() {console.log("onPageHide")}// 返回按钮onBackPress() {console.log("onBackPress")}// 页面销毁aboutToDisappear() {console.log("aboutToDisappear")}build() {Row() {Column() {Text("爆炸现场").fontSize(50).fontWeight(FontWeight.Bold)if (this.isShow) {Boob({isShow:$isShow})} else {Button("已爆炸")}}.width('100%')}.height('100%')}
}@Component
struct Boob {@Link isShow:boolean@State count: number = 10timer: number = 0aboutToAppear() {this.timer=setInterval(() => {this.count--// this.isShow为false时,该组件销毁====》调用aboutToDisappear方法。if(this.count===0){this.isShow=false}console.log(this.count+"")}, 1000)}aboutToDisappear() {clearInterval(this.timer)}build() {Column() {Button("倒计时")Text(this.count+" S").fontSize(20)}}
}

三、页面路由
页面路由指在应用程序中实现不同页面之间的跳转和数据传递。HarmonyOs提供了Router模块,通过不同的ur地址,可以方便地进行页面路由,轻松地访问不同的页面。
Router模块提供了两种跳转模式,分别是router.pushUrl()router.replaceUrl()。这两种模式决定了目标页是否会替换当前页。
router.pushUrl(): 目标页不会替换当前页,而是压入页面栈。这样可以保留当前页的状态,并且可以通过返回键或者调用router.back()方法返回到当前页。
router.replaceUrl(): 目标页会替换当前页,并销毁当前页。这样可以释放当前页的资源,并且无法返回到当前页。
并且Router模块提供了两种实例模式,分别是Standard和Single。这两种模式决定了目标url是否会对应多个实例
Standard: 标准模式,也是默认情况下的实例模式。每次调用该方法都会新建一个目标页,并压入栈顶。
Single: 单例模式。即如果目标页的url在页面栈中已经存在同ur页面,则离栈顶最近的同url页面会被移动到栈顶,并重新加载,如果目标页的url在页面栈中不存在同url页面,则按照标准模式跳转。

router.pushUrl()——>Standard  A跳转到B,栈中有B,还是新建B,A压入栈中,B在A上。

router.pushUrl()——>Single   A跳转到B,栈中有B,不新建B,A压入栈中,已有B提至A上。

router.replaceUrl()——>Standard  A跳转到B,栈中有B,还是新建B,销毁A。B置于栈顶。

 router.replaceUrl()——>Single   A跳转到B,栈中有B,不新建B,销毁A,已有B提至栈顶。


import router from '@ohos.router'@Entry
@Component
struct PageRouter {@State message: string = '努力方向'@State list: Object[] = [{id: 1,name: "房子"}, { id: 2, name: "车子" }, { id: 3, name: "金条" }]build() {Row() {Column() {Text(this.message).fontSize(50).fontWeight(FontWeight.Bold)List() {ForEach(this.list, item => {ListItem() {Text(item.name).fontSize(40).margin({top:10}).fontColor(Color.Orange)}.width('100%').onClick(()=>{router.pushUrl({url:'pages/PageRouterDetail',params:{id:item.id,name:item.name}},router.RouterMode.Standard)})})}}.width('100%')}.height('100%')}onPageShow(){const  param=router.getParams();console.log("PageRouter-onPageShow",JSON.stringify(param))}
}
import router from '@ohos.router'@Entry
@Component
struct PageRouterDetail {@State message: string = '拿到'name: stringaboutToAppear() {const param = router.getParams()const jsp=JSON.stringify(param)console.log("D_aboutToAppear",  jsp)this.name=JSON.parse(jsp).nameconsole.log("D_aboutToAppear", this.name )}build() {Row() {Column() {Text(this.name).fontSize(50).fontWeight(FontWeight.Bold)Button("返回").onClick(() => {this.onReturn1()})}.width('100%')}.height('100%')}onReturn1() {router.showAlertBeforeBackPage({message:'确定要返回吗?'})router.back({url:"pages/PageRouter",params:{id:4,name:"我发财了"}})}
}

四、程序入口

UIAbility是一种包含用户界面的应用组件,主要用于和用户进行交互。UIAbility也是系统调度的单元,为应用提供窗口在其中绘制界面。
每一个UIAbility实例,都对应于一个最近任务列表中的任务。

UIAbility生命周期

UIAbility是在module.json5里面配置的。

import common from '@ohos.app.ability.common'
@Entry
@Component
struct PageEntry {@State message: string = 'Hello World'private context =getContext(this) as common.UIAbilityContextbuild() {Row() {Column() {Text(this.message).fontSize(50).fontWeight(FontWeight.Bold)Button("跳转ability").onClick(()=>{let want={deviceId:"",bundleName:getContext(this.context).applicationInfo.name,//获得包名abilityName:"MoneyAbility",parameters:{name:"随便拿,都是你的了"}}this.context.startAbility(want)})}.width('100%')}.height('100%')}
}
@Entry
@Component
struct PageMoney {@State message: string = '金子银子随便拿'build() {Row() {Column() {Text(this.message).fontSize(50).fontWeight(FontWeight.Bold)}.width('100%')}.height('100%')}
}
{"module": {"name": "entry","type": "entry","description": "$string:module_desc","mainElement": "EntryAbility","deviceTypes": ["phone","tablet"],"deliveryWithInstall": true,"installationFree": false,"pages": "$profile:main_pages","abilities": [{"name": "EntryAbility","srcEntry": "./ets/entryability/EntryAbility.ts","description": "$string:EntryAbility_desc","icon": "$media:icon","label": "$string:EntryAbility_label","startWindowIcon": "$media:icon","startWindowBackground": "$color:start_window_background","exported": true,"skills": [{"entities": ["entity.system.home"],"actions": ["action.system.home"]}]},{"name": "MoneyAbility","srcEntry": "./ets/MoneyAbility/MoneyAbility.ts","description": "$string:EntryAbility_desc","icon": "$media:icon","label": "$string:EntryAbility_label","startWindowIcon": "$media:icon","startWindowBackground": "$color:start_window_background","exported": true}]}
}
import UIAbility from '@ohos.app.ability.UIAbility';
import hilog from '@ohos.hilog';
import window from '@ohos.window';export default class MoneyAbility extends UIAbility {onCreate(want, launchParam) {console.log("MoneyAbility--",want?.parameters?.name)hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');}onDestroy() {hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onDestroy');}onWindowStageCreate(windowStage: window.WindowStage) {// Main window is created, set main page for this abilityhilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate');AppStorage.SetOrCreate("name","房子")windowStage.loadContent('pages/PageMoney',(err, data) => {if (err.code) {hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');return;}hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? '');});}onWindowStageDestroy() {// Main window is destroyed, release UI related resourceshilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageDestroy');}onForeground() {// Ability has brought to foregroundhilog.info(0x0000, 'testTag', '%{public}s', 'Ability onForeground');}onBackground() {// Ability has back to backgroundhilog.info(0x0000, 'testTag', '%{public}s', 'Ability onBackground');}
}

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

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

相关文章

程序汪若依微服务华为云Linux部署保姆教程

若依官方有3个版本,程序汪以前已经出了对应的安装部署视频教程 单应用版本 前后分离版本 微服务版本 本视频是若依微服务版本,如果基础的环境软件都不会安装建议看下程序汪的单应用和前后端分离版本教程, 欢迎点击进入 (单应…

开源流程图表库(01):Mermaid.js生成流程图、时序图、甘特图等

一、Mermaid.js的特点 Mermaid.js是一个用于生成流程图、时序图、甘特图等各种图表的开源库。它使用简洁的文本语法来描述图表结构,并将其转换为可视化的图形。 Mermaid.js的主要特点包括: 简洁易用:Mermaid.js使用简单的文本语法来描述图表…

嵌入式培训3-28

编写一条学生链表&#xff0c;写一些能够像链表里边添加数据的函数 实现&#xff1a;将链表中的所有内容保存到文件中去 以及 读取文件中的所有内容&#xff0c;加载到链表里面 #include <stdio.h> #include <string.h> #include <stdlib.h> #include <ma…

Python爬虫如何快速入门

写了几篇网络爬虫的博文后&#xff0c;有网友留言问Python爬虫如何入门&#xff1f;今天就来了解一下什么是爬虫&#xff0c;如何快速的上手Python爬虫。 一、什么是网络爬虫 网络爬虫&#xff0c;英文名称为Web Crawler或Spider&#xff0c;是一种通过程序在互联网上自动获取…

初识C++之命名空间(namespace)

初识C之入门 命名空间(namespace) 文章目录 初识C之入门 命名空间(namespace)1.为什么要有命名空间2. 命名空间 namespace使用方法3. 作用域限定符(::&#xff09;和 命名空间(namespace)4. 命名空间的定义5. 命名空间的嵌套6. 命名空间的使用7. 总结 1.为什么要有命名空间 在C…

部署elementPlus离线版本

最近项目需要离线开发&#xff0c;不能联网查一些组件的api&#xff0c;于是决定搞一个离线版的文档 一、下载官方文档 下载地址 github地址 gitee地址 选择版本 直接下载压缩包 二、下载live-server插件 全局下载live-server插件 npm i live-server -gvscode下载 三…

Linux split分割xls或csv文件

文件名&#xff1a;test.xls split -a 2 -d -l 100 test.xls test-a 2&#xff1a;后缀是2位 -d&#xff1a;后缀数字 -l 100 &#xff1a;每100行一个文件 test.xls&#xff1a;需要分割的文件名 test&#xff1a;分割后的文件前缀批量修改文件后缀 for i in test*; do mv $…

三位数组合-第12届蓝桥杯选拔赛Python真题精选

[导读]&#xff1a;超平老师的Scratch蓝桥杯真题解读系列在推出之后&#xff0c;受到了广大老师和家长的好评&#xff0c;非常感谢各位的认可和厚爱。作为回馈&#xff0c;超平老师计划推出《Python蓝桥杯真题解析100讲》&#xff0c;这是解读系列的第42讲。 三位数组合&#…

Haproxy负载均衡介绍即部署

haproxy的原理&#xff1a; 提供高可用、负载均衡以及基于TCP&#xff08;四层&#xff09;和HTTP&#xff08;七层&#xff09;应用的代理&#xff0c;支持虚拟主机&#xff0c;开源可靠的一款软件。 适用于哪些负载特别大的web站点&#xff0c;这些站点通常又需要回话保持和七…

Java项目——黑马点评(优惠券秒杀7之Redis消息队列MQ实现异步秒杀)

优惠券秒杀7——Redis消息队列实现异步秒杀 一、问题引出—— 内存溢出—— 之前我们使用的是JDK里面的阻塞队列&#xff0c;而这个队列使用的是JDK里面的内存。如果不加以阻止&#xff0c;在高并发情况下可能会有无数订单对象需要创建并且放到阻塞队列里面。可能会导致将来…

arm 外部中断

main.c: #include"key_inc.h" //封装延时函数 void delay(int ms) {int i,j;for(i0;i<ms;i){for(j0;j<2000;j){}} } int main() {//按键中断的初始化key1_it_config();key2_it_config();key3_it_config();while(1){printf("in main pro\n");delay(1…

C++自主点餐系统

一、 题目 设计一个自助点餐系统&#xff0c;方便顾客自己点餐&#xff0c;并提供对餐厅销售情况的统计和管理功能。 二、 业务流程图 三、 系统功能结构图 四、 类的设计 五、 程序代码与说明 头文件1. SystemMap.h #pragma once #ifndef SYSTEMMAP #define SYSTEMMAP #in…

【八股】泛型

泛型存在的意义&#xff1f; 为了使相同的代码适用于多种数据类型&#xff0c;也就是代码复用。 参数类型上下限限制 <?> 无限制 <? extends E> 声明了类型的上界&#xff0c;表示参数类型可以是他或他的子类。 <? super E> 声明了类型的下界&#xf…

深度学习中的随机种子random_seed

解释 由于模型中的参数初始化例如权重参数如下图&#xff0c;就是随机初始化的&#xff0c;为了能够更好的得到论文中提到效果&#xff0c;可以设置随机种子&#xff0c;从而减少算法结果的随机性&#xff0c;使其接近于原始结果。 设置了随机种子&#xff0c;产生的随机数都…

python、execl数据分析(数据描述)

一 python 1.各函数 1.1python库的安装与导入 #pip install os#pip install matplotlib#pip install seaborn#pip install scikit-learn#pip install scipy#修 改 工 作 目 录import osos.getcwd () # 查看当前工作环境os.chdir( F :\my course\database ) # 修改工作环境o…

linux之Haproxy

介绍 haproxy是一种开源的TCP和HTTP负载均衡代理服务器软件。客户端通过Haproxy代理服务器获得站点页面&#xff0c;而代理服务器收到客户请求后根据负载均衡的规则将请求数据转发给后端真实服务器 下载Haproxy yum install haproxy -y 开启服务 systemctl start haproxy 配…

如何在CentOS使用Docker搭建MinIO容器并实现无公网ip远程访问本地服务

文章目录 前言1. Docker 部署MinIO2. 本地访问MinIO3. Linux安装Cpolar4. 配置MinIO公网地址5. 远程访问MinIO管理界面6. 固定MinIO公网地址 前言 MinIO是一个开源的对象存储服务器&#xff0c;可以在各种环境中运行&#xff0c;例如本地、Docker容器、Kubernetes集群等。它兼…

困难重重!如何将超导量子计算机完好无损地搬进数据中心

内容来源&#xff1a;量子前哨&#xff08;ID&#xff1a;Qforepost&#xff09; 编辑丨慕一 编译/排版丨浪味仙 沛贤 深度好文&#xff1a;3700字丨18分钟阅读 如何把超导量子计算机部署到数据中心&#xff1f;数据中心运营商和量子公司面临着以前没有见过的重重难关。 首…

SqlServer找不到SQL Server Configuration Manager(配置管理)

1、Win键 R &#xff0c;输入 compmgmt.msc 2、找到Sql Server配置管理器

自媒体用ChatGPT批量洗稿软件V5.9环境配置/软件设置教程【汇总】

大家好&#xff0c;我是淘小白~ 首先&#xff0c;感谢大家的支持~~ ChatGPT采集洗稿软件V5.9版本更新&#xff0c;此次版本更新修改增加了一些内容&#xff1a; 1、自定义多条指令&#xff0c;软件自动判断指令条数&#xff0c;进行输入 2、增加谷歌浏览多账号轮询&#xf…