鸿蒙 DevEcoStudio:组件实例(页面及组件生命周期函数)

【使用onPageshow等生命周期函数】

在entry/src/main/ets/pages路径下创建Page1.ets:

复制代码
import router from '@ohos.router'
@Entry
@Component
struct Page1 {
  @State message: string = 'Hello World'
  @State show: boolean=true
  aboutToAppear(){
    console.log('Page1组件创建实例')
  }
  aboutToDisappear(){
    console.log('Page1组件销毁')
  }
  onPageShow(){
    console.log('page1页面展示')
  }
  onPageHide(){
    console.log("page1页面隐藏")
  }
  build() {
      Column() {
        Button('show')
          .onClick(()=>{
            this.show=!this.show
          })
        if (this.show){
          ComponentA()
        }
        Button('跳转到Page2')
          .onClick(()=>{
            router.pushUrl({url:"pages/Page2"})
          })
        Button('跳转到Page3')
          .onClick(()=>{
            router.replaceUrl({url:"pages/Page3"})
          })
      }
      .width('100%')
      .height('100%')
  }
}
@Component
struct ComponentA{
  aboutToAppear(){
    console.log('componentA组件创建实例')
  }
  aboutToDisappear(){
    console.log('componentA组件销毁');
  }
  build(){
    Text('compontent A')
  }
}

在entry/src/main/ets/pages路径下同样创建Page2.ets和Page3.ets:

1.Page2.ets内容:

复制代码
@Entry
@Component
struct Page2 {
  @State message: string = 'Page2内容'
  onPageShow(){
    console.log('page2页面展示')
  }
  onPageHide(){
    console.log("page2页面隐藏")
  }
  onBackPress(){
    console.log("Page2页面返回")
  }
  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
      }
      .width('100%')
    }
    .height('100%')
  }
}

2.Page3.ets内容:

复制代码
@Entry
@Component
struct Page3 {
  @State message: string = 'Page3内容'
  onPageShow(){
    console.log('page3页面展示')
  }
  onPageHide(){
    console.log("page3页面隐藏")
  }
  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
      }
      .width('100%')
    }
    .height('100%')
  }
}

在下边点击Log->HiLog,中间最左边的下拉菜单选择Phone,查看效果,如图:

相关推荐
OH_TPC4 小时前
ImageKnifePro 源码解读(四):降采样策略族——按显示尺寸改衣服,不按原尺寸硬塞
harmonyos
民办二本的神4 小时前
AI 助手升级后聊天记录又丢了(二):数据一直都在,丢的是"看见"
harmonyos
huang_xiaoen1 天前
鸿蒙手机远程控制电脑哪个好用?2026鸿蒙远控软件横测推荐
华为·harmonyos·远程工作·远程工具·远程办公
爱写Bug的浮游2 天前
初识仓颉:5 分钟看懂核心语法
harmonyos·编程语言
羽落•无痕(苏晗默)2 天前
华为数通IA——14、网络服务与应用:TCP/UDP 传输层协议与 FTP、Telnet、SSH 实践
网络·网络协议·tcp/ip·网络安全·华为·udp·信息与通信
程序猿追3 天前
鸿蒙 PC 的 Ionic 工单有两个错误,按下生成后光标该去哪儿
华为·harmonyos
KevinChaos3 天前
随手备忘录手记 04|HarmonyOS 7.0新特性实验:物品图鉴的加载逻辑
华为·harmonyos
Sirius_Ji3 天前
从硬解基座到字幕与滤镜链:ffmpeg-for-HarmonyOS v0.3.2
harmonyos
用户86194177207413 天前
uni-app 鸿蒙端提现点不动?我用 UTS 插件补上了微信"确认收款"
微信·harmonyos
码间留白3 天前
uni-app 鸿蒙端提现点不动?我用 UTS 插件补上了微信"确认收款"
uni-app·harmonyos·鸿蒙·uts插件·微信商家转账