HarmonyOS 鸿蒙Next 传值问题

发布于 1周前 作者 gougou168 来自 鸿蒙OS

HarmonyOS 鸿蒙Next 传值问题 给了一个object类型,该怎么接收啊

map是瞎写的,还有我传了一个rawfile的字符串,为什么会显示找不到该文件,使用api10


更多关于HarmonyOS 鸿蒙Next 传值问题的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html

17 回复

虽然object可以用ESObject,但官方这边建议不要使用object,改用class或interface代替,如果不确定里面有什么,可以用Record<string,string|number|boolean>这种代替,你这边例子已经有了position了,所以把object替换position就行了。

import router from '@ohos.router'

// import { PageTitle }  from '../../components/Common'
// import { position, user } from '../../types/Interface'
export interface position {
  name: string
  id: number
  children?: position[]
}

class user {
  name?: string
  imgSrc?: string
  isOnline?: boolean
  sex?: number
  position?: string
}

@Component
struct PageTitle {
  @Prop title: string
  @Prop isSearch: boolean

  build() {
  }
}

//审计署
@Entry
@Component
struct Page176 {
  @State searchValue: string = ''
  @State topNavArr: position[] = []
  @State curListDate: position[] | undefined = []
  // @State exactName: string|number = router.getParams()['name']|0
  @State exactName: undefined = undefined
  private listData: position[] = [{
    name: '湖南省审计厅', id: 10000, children: [
      { name: '湖南省审计厅本级', id: 11000, },
      {
        name: '湖南省审计厅下级', id: 12000, children: [
        {
          name: '湘潭市审计局', id: 12100, children: [
          { name: '湘潭市审计局本级', id: 12110 },
          {
            name: '湘潭市审计局下级', id: 12120, children: [
            { name: '湘潭市审计局下级1', id: 12121 },
            { name: '湘潭市审计局下级1', id: 12122 }
          ]
          },
        ]
        },
        { name: '长沙市审计局', id: 12000 }]
      }
    ]
  }]
  private userList: user[] = [
    {
      name: '用户名1',
      imgSrc: 'person (1).jpg',
      isOnline: true,
      sex: 0,
      position: '职位名称1'
    },
    {
      name: '用户名2',
      imgSrc: 'person (2).jpg',
      isOnline: false,
      sex: 1,
      position: '职位名称2'
    }
  ]

  aboutToAppear() {

    if (this.exactName) {

      this.topNavArr.push(this.listData[0])
      this.curListDate = this.listData[0].children
    } else {
      this.topNavArr.push(this.listData[0])
      this.curListDate = this.listData[0].children
      // console.info(this.exactName)
    }
  }

  build() {
    Column() {
      PageTitle({ title: '地方审计机关', isSearch: true })

      // 面包屑
      Scroll() {
        Row({ space: 3 }) {
          ForEach(this.topNavArr, (item: position, index) => {
            if (index > 0) {
              Image($r('app.media.icon'))
                .width(8)
                .height(8)
            }
            Text(item.name)
              .fontSize(13)
              .fontColor(this.topNavArr.length - 1 == index ? '#333' : '#0184fa')
              .onClick(() => {
                this.topNavArr = this.topNavArr.slice(0, index + 1)
                this.curListDate = item.children
              })
          })
        }
        .constraintSize({ minWidth: '100%' })
        .padding({ left: 16, right: 16, top: 12, bottom: 12 })
        .justifyContent(FlexAlign.Start)
        .border({ width: { bottom: 1 }, color: '#f2f2f2' })
      }
      .scrollable(ScrollDirection.Horizontal)
      .scrollBar(BarState.Off)

      // 列表栏
      List() {
        ListItemGroup() {
          ForEach(this.curListDate, (item: position) => {
            ListItem() {
              ListLine1({ item })
                .onClick(() => {
                  if (item.children) {
                    this.topNavArr.push(item)
                    this.curListDate = item.children
                    console.log(item.name)
                  } else {
                    this.topNavArr.push(item)
                    this.curListDate = []
                  }
                })
            }
          })
        }

        ListItemGroup() {
          ForEach(this.userList, (item: position) => {
            ListItem() {
              ListLine2({ userInfo: item })
                .onClick(() => {
                  router.pushUrl({ url: 'pages/chat/DataCardPage' })
                })
            }
          })
        }
      }
      .height('100%')
      .width('100%')
      .backgroundColor("#f9f9f9")
    }
  }
}

@Component
// 上层级单位
struct ListLine1 {
  private item: object = new Map();

  build() {
    Row() {
      Text(this.item['name'])
        .fontSize(16)
      Image($r('app.media.icon'))
        .width(15)
        .height(15)
    }
    .backgroundColor('#fff')
    .width('100%')
    .justifyContent(FlexAlign.SpaceBetween)
    .padding(16)
  }
}

//下层级单位
@Component
struct ListLine2 {
  private userInfo: object = new Map();

  build() {
    Row() {
      Image($rawfile('artboard_01.png'))
        .fancyImage(48, 48)
        .margin({ right: 8 })
        .backgroundColor('f9f9f9')
        .borderRadius(4)

      Column({ space: 8 }) {
        Row({ space: 6 }) {
          Text(this.userInfo['name'])
            .fontSize(16)
            .fontWeight(FontWeight.Regular)
            .fontColor('#333')
          if (this.userInfo['sex'] == 0) {
            Image($r('app.media.icon_2'))
              .fancyImage(16, 16)
          } else {
            Image($r('app.media.icon_2'))
              .fancyImage(16, 16)
          }
          if (this.userInfo['isOnline']) {
            Text('[在线]')
              .fancyText(14, 'regular', '#0184FA')
          } else {
            Text('[离线]')
              .fancyText(14, 'regular', '#7F7F7F')
          }
        }

        Text(this.userInfo['position'])
          .fancyText(14, 'regular', '#7F7F7F')
      }
      .alignItems(HorizontalAlign.Start)
    }
    .padding({ left: 16, top: 8, bottom: 8 })
    .width('100%')
    .backgroundColor('#fff')
  }
}

@Extend(Image)
function fancyImage(width: number, height: number) {
  .width(width).height(height)
}

@Extend(Text)
function fancyText(size: number, weight: string, color: string,) {
  .fontSize(size)
  .fontWeight(weight)
  .fontColor(color)
}

更多关于HarmonyOS 鸿蒙Next 传值问题的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


我看到你的子组件没有进行修改呀
map只是我临时加上去的,

找HarmonyOS工作还需要会Flutter的哦,有需要Flutter教程的可以学学大地老师的教程,很不错,B站免费学的哦:BV1S4411E7LY/?p=17

我是针对你截图画红框的改的,把object替换position,你那边现在的需求是什么?

找HarmonyOS工作还需要会Flutter的哦,有需要Flutter教程的可以学学大地老师的教程,很不错,B站免费学的哦:BV1S4411E7LY/?p=17

试着用模板字符串Image($rawfile(xxxx))

对,直接将对应类型的对象传进去就行。

import router from '@ohos.router'

// import { PageTitle }  from '../../components/Common'
// import { position, user } from '../../types/Interface'
export interface position {
  name: string
  id: number
  children?: position[]
}

class user {
  name?: string
  imgSrc?: string
  isOnline?: boolean
  sex?: number
  position?: string
}

@Component
struct PageTitle {
  @Prop title: string
  @Prop isSearch: boolean

  build() {}
}

//审计署
@Entry
@Component
struct Page178 {
  @State searchValue: string = ''
  @State topNavArr: position[] = []
  @State curListDate: position[] | undefined = []
  @State exactName: undefined = undefined
  private listData: position[] = [{
    name: '湖南省审计厅', id: 10000, children: [
      { name: '湖南省审计厅本级', id: 11000, },
      {
        name: '湖南省审计厅下级', id: 12000, children: [
        {
          name: '湘潭市审计局', id: 12100, children: [
          { name: '湘潭市审计局本级', id: 12110 },
          {
            name: '湘潭市审计局下级', id: 12120, children: [
            { name: '湘潭市审计局下级1', id: 12121 },
            { name: '湘潭市审计局下级1', id: 12122 }
          ]
          },
        ]
        },
        { name: '长沙市审计局', id: 12000 }]
      }
    ]
  }]
  private userList: user[] = [
    {
      name: '用户名1',
      imgSrc: 'person (1).jpg',
      isOnline: true,
      sex: 0,
      position: '职位名称1'
    },
    {
      name: '用户名2',
      imgSrc: 'person (2).jpg',
      isOnline: false,
      sex: 1,
      position: '职位名称2'
    }
  ]

  aboutToAppear() {

    if (this.exactName) {

      this.topNavArr.push(this.listData[0])
      this.curListDate = this.listData[0].children
    } else {
      this.topNavArr.push(this.listData[0])
      this.curListDate = this.listData[0].children
      // console.info(this.exactName)
    }
  }

  build() {
    Column() {
      PageTitle({ title: '地方审计机关', isSearch: true })

      // 面包屑
      Scroll() {
        Row({ space: 3 }) {
          ForEach(this.topNavArr, (item: position, index) => {
            if (index > 0) {
              Image($r('app.media.icon'))
                .width(8)
                .height(8)
            }
            Text(item.name)
              .fontSize(13)
              .fontColor(this.topNavArr.length - 1 == index ? '#333' : '#0184fa')
              .onClick(() => {
                this.topNavArr = this.topNavArr.slice(0, index + 1)
                this.curListDate = item.children
              })
          })
        }
        .constraintSize({ minWidth: '100%' })
        .padding({ left: 16, right: 16, top: 12, bottom: 12 })
        .justifyContent(FlexAlign.Start)
        .border({ width: { bottom: 1 }, color: '#f2f2f2' })
      }
      .scrollable(ScrollDirection.Horizontal)
      .scrollBar(BarState.Off)

      // 列表栏
      List() {
        ListItemGroup() {
          ForEach(this.curListDate, (item: position) => {
            ListItem() {
              ListLine1({ item })
                .onClick(() => {
                  if (item.children) {
                    this.topNavArr.push(item)
                    this.curListDate = item.children
                    console.log(item.name)
                  } else {
                    this.topNavArr.push(item)
                    this.curListDate = []
                  }
                })
            }
          })
        }

        ListItemGroup() {
          ForEach(this.userList, (item: user) => {
            ListItem() {
              ListLine2({ userInfo: item })
                .onClick(() => {
                  router.pushUrl({ url: 'pages/chat/DataCardPage' })
                })
            }
          })
        }
      }
      .height('100%')
      .width('100%')
      .backgroundColor("#f9f9f9")
    }
  }
}

@Component
// 上层级单位
struct ListLine1 {
  @Prop item: position

  build() {
    Row() {
      Text(this.item.name)
        .fontSize(16)
      Image($r('app.media.icon'))
        .width(15)
        .height(15)
    }
    .backgroundColor('#fff')
    .width('100%')
    .justifyContent(FlexAlign.SpaceBetween)
    .padding(16)
  }
}

//下层级单位
@Component
struct ListLine2 {
  @Prop userInfo: user

  build() {
    Row() {
      Image($rawfile('artboard_01.png'))
        .fancyImage(48, 48)
        .margin({ right: 8 })
        .backgroundColor('f9f9f9')
        .borderRadius(4)

      Column({ space: 8 }) {
        Row({ space: 6 }) {
          Text(this.userInfo.name)
            .fontSize(16)
            .fontWeight(FontWeight.Regular)
            .fontColor('#333')
          if (this.userInfo.sex == 0) {
            Image($r('app.media.icon_2'))
              .fancyImage(16, 16)
          } else {
            Image($r('app.media.icon_2'))
              .fancyImage(16, 16)
          }
          if (this.userInfo.isOnline) {
            Text('[在线]')
              .fancyText(14, 'regular', '#0184FA')
          } else {
            Text('[离线]')
              .fancyText(14, 'regular', '#7F7F7F')
          }
        }

        Text(this.userInfo.position)
          .fancyText(14, 'regular', '#7F7F7F')
      }
      .alignItems(HorizontalAlign.Start)
    }
    .padding({ left: 16, top: 8, bottom: 8 })
    .width('100%')
    .backgroundColor('#fff')
  }
}

@Extend(Image)
function fancyImage(width: number, height: number) {
  .width(width).height(height)
}

@Extend(Text)
function fancyText(size: number, weight: string, color: string,) {
  .fontSize(size)
  .fontWeight(weight)
  .fontColor(color)
}

重点关注:

1、ArkTS 对JS代码的对象使用进行了一些更严格的要求,相应的TS代码的一些类型相关使用也做了用法建议,细节参考文档:https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/quick-start/arkts-more-cases.md

2、如上所述如果要传递对象,最好声明一个类来给出确定类型而非使用开放对象类型;

3、如果父子组件进行对象数组的元素传递时,通常要用@Obseved装饰相关对象类,用@State装饰父组件中的对象数组变量,用@ObjectLink装饰子组件中的数组元素对象变量;这样的组合能保证父子组件的UI可随此对象数组变化而刷新;具体示例也可参考文档:https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V2/arkts-observed-and-objectlink-0000001473697338-V2#section99561777591

4、有关 rawfile 资源,字符串要用文件全名,后缀不可省;即 image.jpg 而非 image。

希望有帮助!

我用的是全名,

可以通过在代码中使用一个$rawfile('imgSrc')来验证,如果这个不报错则全名没问题。

第一,为什么用object 这个类型,可以自己写model,
第二个问题:个rawfile的字符串,为什么会显示找不到该文件

是因为你那个userInfo 是一个map, map 的取值方式是你写的那样的方式吗

根本的原因就是你传递的值不是一个强类型的

那应该怎么定义这个类型,

可以用ESObject,或者发完整的示例demo,我改好后发给你。

姓名:张三 职位:软件工程师 简介:

  • 擅长Java和Python编程
  • 熟悉Spring Boot和Django框架
  • 有5年项目开发经验

在HarmonyOS(鸿蒙)Next中,传值问题主要涉及组件之间的数据传递。鸿蒙系统提供了多种传值机制,包括Intent、AbilitySlice、DataAbility等。

  1. Intent传值:Intent是鸿蒙系统中用于组件间通信的主要方式。通过Intent可以在不同Ability或AbilitySlice之间传递数据。使用Intent.setParams()方法可以设置传递的参数,接收方通过Intent.getParams()获取数据。

  2. AbilitySlice传值:AbilitySlice是鸿蒙系统中用于管理UI的组件。在同一个Ability中,不同AbilitySlice之间可以通过present()方法传递数据。通过Intent对象携带参数,接收方在onStart()方法中获取数据。

  3. DataAbility传值:DataAbility是鸿蒙系统中用于数据共享的组件。通过DataAbility可以实现跨应用的数据传递。使用DataAbilityHelper类可以访问DataAbility,并通过insert()query()等方法进行数据操作。

  4. EventBus传值:鸿蒙系统支持使用EventBus进行组件间的消息传递。通过发布和订阅事件,可以在不同组件之间传递数据。使用EventBus.getInstance().post()发布事件,接收方通过@Subscribe注解订阅事件并处理数据。

  5. SharedPreferences传值:鸿蒙系统支持使用SharedPreferences进行轻量级数据存储和传递。通过Preferences.getDefaultPreferences()获取SharedPreferences对象,使用putString()getString()等方法进行数据存取。

以上是鸿蒙Next中常见的传值方式,开发者可以根据具体需求选择合适的方法进行数据传递。

在HarmonyOS(鸿蒙)Next中,传值问题通常涉及页面间或组件间的数据传递。常见方法包括:

  1. Intent传值:通过Intent对象在页面间传递数据,支持基本类型、Parcelable和Serializable对象。
  2. AbilitySlice传值:在AbilitySlice中使用startAbilityForResult方法,通过Intent传递数据并接收返回结果。
  3. EventBus:使用事件总线机制,通过发布和订阅事件实现跨组件传值。
  4. SharedPreferences:适用于存储少量简单数据,适合跨页面共享配置或状态。
  5. 数据库或文件存储:对于大量或复杂数据,可以使用数据库或文件存储,在需要时读取。

选择合适的方法取决于具体场景和需求。

回到顶部
AI 助手
你好,我是IT营的 AI 助手
您可以尝试点击下方的快捷入口开启体验!