HarmonyOS状态管理:@State与@Prop、@Link的示例

参考官方文档:https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V2/arkts-component-state-management-0000001524417205-V2

@State与@Prop

  • 父子组件之间进行数据传递和同步

  • 单向传递,State-->Prop 父只能传递给子

    //父的数据只能传给子
    //State --->Prop 单向的
    @Component
    struct upProp {
    //子
    @Prop content_prop: string

    build() {
    Column() {
    Text('Prop:' + this.content_prop)
    .textSty()
    Button('修改prop数据')
    .btnSty(() => {
    this.content_prop = '我是单向的'
    })
    }

    }
    }

  • 父子组件之间进行数据传递和同步

  • 双向传递,State<-->Link

    //存放一个 @Link装饰的状态数据
    //双向的
    @Component
    struct upLink {
    //子
    @Link content_link: string

    复制代码
    build() {
      Column() {
        Text(`Link:${this.content_link}`)
          .textSty()
        Button('修改link数据')
          .btnSty(() => {
            this.content_link = '我是双向的'
          })
      }
    }

    }

完整示例:

复制代码
@Entry
@Component
struct testState {
  //父
  @State name: string = "JasonYin"

  build() {
    Column({ space: 0 }) {
      Text(this.name)
        .textSty()
      Divider()
      Button('点我点我')
        .btnSty(() => {
          this.name = this.name === 'JasonYin' ? 'HarmonyOS4.0' : 'JasonYin'
        })
      Divider()
      upProp({ content_prop: this.name })
      Divider()
      //如果是 state < --- > link 参数传递时,使用 $变量名 进行传递
      upLink({ content_link: $name })
    }

  }
}

//父的数据只能传给子
//State --->Prop  单向的
@Component
struct upProp {
  //子
  @Prop content_prop: string

  build() {
    Column() {
      Text('Prop:' + this.content_prop)
        .textSty()
      Button('修改prop数据')
        .btnSty(() => {
          this.content_prop = '我是单向的'
        })
    }

  }
}

//存放一个 @Link装饰的状态数据
//双向的
@Component
struct upLink {
  //子
  @Link content_link: string

  build() {
    Column() {
      Text(`Link:${this.content_link}`)
        .textSty()
      Button('修改link数据')
        .btnSty(() => {
          this.content_link = '我是双向的'
        })
    }
  }
}

@Extend(Button) function btnSty(click: Function) {
  .fontSize(33)
  .onClick(() => {
    click()
  })
}

@Extend(Text) function textSty() {
  .fontSize(30)
  .fontWeight(FontWeight.Bold)
  .fontColor(Color.Green)
}
相关推荐
看到我,请让我去学习27 分钟前
OpenCV 与深度学习:从图像分类到目标检测技术
深度学习·opencv·分类
加油加油的大力42 分钟前
入门基于深度学习(以yolov8和unet为例)的计算机视觉领域的学习路线
深度学习·yolo·计算机视觉
财经三剑客3 小时前
鸿蒙智行6月交付新车52747辆 单日交付量3651辆
华为·harmonyos
IRevers3 小时前
【自动驾驶】经典LSS算法解析——深度估计
人工智能·python·深度学习·算法·机器学习·自动驾驶
睿麒3 小时前
鸿蒙app 开发中的 map 映射方式和用法
华为·harmonyos
学废了wuwu3 小时前
深度学习归一化方法维度参数详解(C/H/W/D完全解析)
c语言·人工智能·深度学习
whabc1003 小时前
和鲸社区深度学习基础训练营2025年关卡4
人工智能·深度学习
whabc1003 小时前
和鲸社区深度学习基础训练营2025年关卡2(3)pytorch
人工智能·深度学习·sklearn
学废了wuwu3 小时前
深度学习中的归一化技术详解:BN、LN、IN、GN
人工智能·深度学习
MUTA️3 小时前
《MAE: Masked Autoencoders Are Scalable Vision Learners》论文精读笔记
人工智能·笔记·深度学习·transformer