HarmonyOS router页面跳转

默认启动页面index.ets

复制代码
import  router from '@ohos.router'
import  {BusinessError} from '@ohos.base'

@Entry
@Component
struct Index {
  @State message: string = 'Hello World';

  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)

        //添加按钮,以响应用户点击
        Button(){
          Text('Next')
            .fontSize(30)
            .fontWeight(FontWeight.Bold)
        }
        .type(ButtonType.Capsule)
        .margin({
          top:20
        })
        .backgroundColor('#00D9FFB')
        .width('40%')
        .height('5%')
        //跳转按钮绑定onclick事件,点击跳转到目标页面
        .onClick(()=>{
          console.log(`Succeeded in clicking the 'Next' button.`);
          router.pushUrl({url:'pages/TargetPage'}).then(()=>{
            console.info('Succeeded in jumping to the second page.')
          }).catch((err: BusinessError) => {
            console.error(`Failed to jump to the second page.Code is ${err.code}, message is ${err.message}`)
          })
        })
      }
      .width('100%')
    }
    .height('100%')
  }
}

跳转目标页面TargetPage.ets

复制代码
// 导入页面路由模块
import router from '@ohos.router';
import { BusinessError } from '@ohos.base';

@Entry
@Component
struct TargetPage {
  @State message: string = '鸿蒙小趣';

  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
        Button(){
          Text('Back')
            .fontSize(25)
            .fontWeight(FontWeight.Bold)
        }
        .type(ButtonType.Capsule)
        .margin({top:20})
        .backgroundColor('#0D9FFB')
        .width('40%')
        .height('5%')
        // 返回按钮绑定onClick事件,点击按钮时返回到第一页
        .onClick(()=>{
          console.info(`Succeeded in clicking the 'Back' button.`)
          try {
            // 返回第一页
            router.back()
            console.info('Succeeded in returning to the first page.')
          }catch (err){
            let code = (err as BusinessError).code;
            let message = (err as BusinessError).message;
            console.error(`Failed to return to the first page.Code is ${code}, message is ${message}`)
          }
        })
      }
      .width('100%')
    }
    .height('100%')
  }
}

运行效果图如下:

相关推荐
OH_TPC2 小时前
【鸿蒙优选三方库】@react-native-ohos/react-native-screens:原生屏幕导航管理
华为·harmonyos·鸿蒙
FrameNotWork7 小时前
HarmonyOS应用《左右相册》 智感握姿实战:让操作按钮自动“站“到你拇指够得到的地方
华为·harmonyos
hacker7077 小时前
DBeaver 鸿蒙 PC 适配全记录:在 HarmonyOS 桌面端原生重建一个通用数据库工具
数据库·华为·harmonyos
hacker7078 小时前
DBeaver Community 鸿蒙 PC 适配全记录:在 HarmonyOS PC 上运行原生数据库管理工具
数据库·华为·harmonyos
HwJack209 小时前
用 HML + CSS + JS 三段式写鸿蒙界面
javascript·css·harmonyos
小雨青年18 小时前
【HarmonyOS 7 平行视界深度实战】06 页面路由、返回栈与多层跳转怎么处理
华为·harmonyos
2501_919749031 天前
华为鸿蒙免费刷题软件—小羊免费刷题
华为·harmonyos·鸿蒙
游戏智眼1 天前
HarmonyOS 7 适配升级:NIM SDK 释放端侧 AI 与网络能力
人工智能·harmonyos