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)
}
相关推荐
workflower17 分钟前
案例:大模型驱动的“发现- 研判- 整改- 验证”全闭环治理体系
人工智能·深度学习·机器学习·设计模式·机器人
HMS Core1 小时前
借助AR Engine人脸识别与跟踪能力,直播不露脸也生动
ar·harmonyos
ZhouDevin1 小时前
算法论文/模型微调1——CNN架构做lora微调训练
人工智能·深度学习·算法·架构·cnn
云端漫步19872 小时前
HarmonyOS NEXT AI 智能生活助手:AI 日程规划
人工智能·华为·生活·harmonyos
高洁013 小时前
VLA:驱动具身智能迈向通用的关键引擎
人工智能·python·深度学习·transformer·知识图谱
AI人工智能+3 小时前
学位证书识别技术通过计算机视觉、自然语言处理和大模型推理相结合,实现了高精度、高效率的证书数字化处理
深度学习·计算机视觉·自然语言处理·ocr·学位证书识别
过期的秋刀鱼!4 小时前
机器学习开发的迭代循环
人工智能·python·深度学习·神经网络·机器学习
向哆哆5 小时前
水稻病害检测数据集分享(适用于YOLO系列深度学习分类检测任务)
深度学习·yolo·分类
达子6665 小时前
第25章_HarmonyOs开发图解之 电话服务
华为·harmonyos
林泽毅5 小时前
PyTRIO快速入门实战篇(二):用 GRPO 提升 GSM8K 数学推理准确率
人工智能·深度学习·机器学习·llm·强化学习