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)
}
相关推荐
carpell11 分钟前
【语义分割专栏】3:Segnet实战篇(附上完整可运行的代码pytorch)
人工智能·python·深度学习·计算机视觉·语义分割
mengyoufengyu33 分钟前
DeepSeek11-Ollama + Open WebUI 搭建本地 RAG 知识库全流程指南
人工智能·深度学习·deepseek
程序员小刘1 小时前
【HarmonyOS 5】运动健康开发实践介绍以及详细案例
华为·harmonyos
御承扬1 小时前
从零开始开发纯血鸿蒙应用之网络检测
网络·华为·harmonyos
vlln1 小时前
2025年与2030年AI及AI智能体 (Agent) 市场份额分析报告
人工智能·深度学习·神经网络·ai
GiantGo2 小时前
信息最大化(Information Maximization)
深度学习·无监督学习·信息最大化
Blossom.1189 小时前
使用Python和Scikit-Learn实现机器学习模型调优
开发语言·人工智能·python·深度学习·目标检测·机器学习·scikit-learn
scdifsn10 小时前
动手学深度学习12.7. 参数服务器-笔记&练习(PyTorch)
pytorch·笔记·深度学习·分布式计算·数据并行·参数服务器
海盗儿11 小时前
Attention Is All You Need (Transformer) 以及Transformer pytorch实现
pytorch·深度学习·transformer
不爱写代码的玉子12 小时前
HALCON透视矩阵
人工智能·深度学习·线性代数·算法·计算机视觉·矩阵·c#