构建第一个ArkTS应用(FA模型)

时间:2024-04-06 18:57:12
  • 第一个页面跳转到第二个页面。

    在第一个页面中,跳转按钮绑定onClick事件,点击按钮时跳转到第二页。“index.ets”文件的示例如下:

     
    // index.ets
    // 导入页面路由模块
    import router from '@ohos.router';
    
    @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('#0D9FFB')
            .width('40%')
            .height('5%')
            // 跳转按钮绑定onClick事件,点击时跳转到第二页
            .onClick(() => {
              router.push({ url: 'pages/second' })
              // 若为API 9工程,则可使用以下接口
              // router.pushUrl({ url: 'pages/second' })
            })
          }
          .width('100%')
        }
        .height('100%')
      }
    }

  • 第二个页面返回到第一个页面。

    在第二个页面中,返回按钮绑定onClick事件,点击按钮时返回到第一页。“second.ets”文件的示例如下:

    // second.ets
    // 导入页面路由模块
    import router from '@ohos.router';
    
    @Entry
    @Component
    struct Second {
      @State message: string = 'Hi there'
    
      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(() => {
              router.back()
            })
          }
          .width('100%')
        }
        .height('100%')
      }
    }

  • 打开index.ets文件,点击预览器中的

    按钮进行刷新。效果如下图所示: