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)
}
相关推荐
算法金「全网同名」4 小时前
算法金 | 时间序列预测真的需要深度学习模型吗?是的,我需要。不,你不需要?
深度学习·机器学习·数据分析
SEU-WYL4 小时前
基于深度学习的文本框检测
人工智能·深度学习·dnn
B站计算机毕业设计超人4 小时前
计算机毕业设计Python深度学习美食推荐系统 美食可视化 美食数据分析大屏 美食爬虫 美团爬虫 机器学习 大数据毕业设计 Django Vue.js
大数据·python·深度学习·机器学习·数据分析·课程设计·推荐算法
夕小瑶5 小时前
守口如瓶,OpenAI刻意隐瞒的黑客攻击事件时隔一年被证实
人工智能·深度学习·机器学习·自然语言处理
龙的爹23335 小时前
论文 | Measuring and Narrowing the Compositionality Gap in Language Models
人工智能·深度学习·机器学习
樱花的浪漫5 小时前
将大型语言模型模块化打造协作智能体
人工智能·深度学习·语言模型·自然语言处理·知识图谱·agent
张紫娃6 小时前
【鸿蒙学习笔记】页面布局
笔记·学习·harmonyos
Bunny_Ben6 小时前
理解机器学习中的潜在空间(Understanding Latent Space in Machine Learning)
人工智能·笔记·深度学习·神经网络·机器学习
SEU-WYL7 小时前
基于深度学习的环绕文字识别
人工智能·深度学习·dnn
开心星人7 小时前
【深度学习】循环神经网络RNN、LSTM、GRU
rnn·深度学习·lstm