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)
}
相关推荐
抖音开放平台1 小时前
【重磅】用AI玩转抖音,抖音CLI全面发布
深度学习·aigc·产品
程序猿追2 小时前
HarmonyOS 7 阅读页换一套配色后怎样记住上次选择
华为·harmonyos
程序猿追2 小时前
HarmonyOS 7 本机书签里,两篇同名文章怎样在重启后各自打开
大数据·数据分析·harmonyos
程序猿追2 小时前
HarmonyOS 7 待办桌面卡片,划掉一项后谁来更新桌面
华为·harmonyos
默 语2 小时前
HarmonyOS7 组件通用事件(三):onAreaChange 区域变化事件——位置动了它知道,offset 动了它装没看见
harmonyos
kyh10033811203 小时前
从仿生学到深度学习:人工神经网络原理解析
人工智能·python·深度学习
落798.3 小时前
generate()不是一个算子:从 ops-transformer 看大模型计算如何落到昇腾 NPU
人工智能·深度学习·transformer
钉先生贾4 小时前
HarmonyOS 7.0 工程升级实战 49:发布候选与正式配置分叉时,怎样保证可逆回退
华为·harmonyos
qq_25294131684 小时前
道路自然灾害障碍检测数据集深度学习 目标检测 道路灾害 滑坡落石 智能巡检 YOLO格式 数据集发布9084期
深度学习·yolo·目标检测
阿enna4 小时前
把本地数据与权重迁移到服务器并启动训练(进阶)
运维·服务器·深度学习·yolo·目标检测·cnn·视觉检测