HarmonyOS父子组件转达参数

[复制链接]
发表于 2026-1-26 17:21:00 | 显示全部楼层 |阅读模式
HarmonyOS父子组件转达参数

1. 使用@State和@Prop举行父子组件转达———注意是单向同步

@Prop装饰器:父子单向同步

      
  • 注意:只支持单向同步,同时也只能支持string\number\boolean\enum比力简单的范例。

代码
  1. // 使用 props 进行父子组件传值
  2. @Component
  3. struct SonCom {
  4.    
  5.    
  6.   // 父子间传递过来的数据使用 @Prop 进行接受
  7.   @Prop sonCar: string
  8.   // 修改传递的参数
  9.   changeInfo = (info: string)=> {
  10.    
  11.    }
  12.   build() {
  13.    
  14.    
  15.     Column() {
  16.    
  17.    
  18.       Text(`这是子组件的盒子--- ${
  19.      
  20.      this.sonCar}`)
  21.       Button('子组件修改父组件的数据').onClick((event: ClickEvent) => {
  22.    
  23.    
  24.         this.changeInfo('吉利银河 L7 ----' + Math.ceil(Math.random() * 10))
  25.       })
  26.     }
  27.     .width('100%')
  28.     .height(100)
  29.     .backgroundColor(Color.Orange)
  30.   }
  31. }
  32. @Entry
  33. @Component
  34. struct PropsPage {
  35.    
  36.    
  37.   @State info: string = '比亚迪 宋'
  38.   changeInfo = (newInfo: string)=>{
  39.    
  40.    
  41.     this.info = newInfo
  42.   }
  43.   build() {
  44.    
  45.    
  46.     Column({
  47.    
  48.     space: 20}) {
  49.    
  50.    
  51.       Text(`这是父组件的盒子 ${
  52.      
  53.      this.info}`)
  54.       Button('修改父组件的数据').onClick((event: ClickEvent) => {
  55.    
  56.    
  57.         this.info = '领克 08---' + Math.ceil(Math.random() * 10)
  58.       })
  59.       // 这是子组件
  60.       SonCom({
  61.    
  62.    
  63.         sonCar: this.info,
  64.         changeInfo: this.changeInfo
  65.       })
  66.     }
  67.     .width('100%')
  68.     .height(300)
  69.     .backgroundColor(Color.Pink)
  70.   }
  71. }
复制代码
演示

2. @Link装饰器:父子双向同步

@Link装饰器:父子双向同步

      
  • 注意

  1. // 子组件
  2. @Component
  3. struct ChildCom {
  4.    
  5.    
  6.   @Link list: number[]
  7.   build() {
  8.    
  9.    
  10.     Column() {
  11.    
  12.    
  13.       List({
  14.    
  15.    space: 10}) {
  16.    
  17.    
  18.         ForEach
复制代码

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

×
回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表