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)
}
相关推荐
147API3 分钟前
蒸馏项目什么时候该停,怎样切换到RAG、微调或模型路由
人工智能·深度学习·机器学习·数据挖掘
贾伟康16 分钟前
【时光清单|19】HarmonyOS ArkTS 回归测试实战:覆盖启动、空数据、异常输入和重复点击
软件测试·harmonyos·arkts·回归测试·hypium
坚果的博客1 小时前
Flutter OHOS 环境搭建实战:oh-3.44.9-dev 从 0 到 1 完整记录
flutter·华为·harmonyos
坚果的博客1 小时前
认识 CPF-RN:React Native 鸿蒙官方社区与四大核心仓库
react native·react.js·harmonyos
YOLO视觉与编程1 小时前
YOLO / Labelme目标分割数据集增强扩充软件v1.0.0适用于YOLO全版本
人工智能·深度学习·yolo·计算机视觉
茗鹤APS和MES1 小时前
工业排产:AI可赋能,APS不可替代
人工智能·深度学习·机器学习
大雷神2 小时前
HarmonyOS ArkGraphics 2D可变帧率实操——同屏对比30、60和90 FPS动画
华为·harmonyos
OH_TPC2 小时前
【鸿蒙优选三方库】@react-native-ohos/react-native-fast-image:高性能图片加载与缓存组件
缓存·华为·harmonyos·鸿蒙
程序猿编码2 小时前
基于GGML的C++17轻量化语音推理引擎:说话人识别与语音分析技术全解析
开发语言·c++·pytorch·深度学习·神经网络·大模型
jay神3 小时前
深度学习如何确定Batch Size的大小?
人工智能·深度学习·计算机视觉·毕业设计·课程设计·batch