组件状态管理 及 父子组件传值
相关博客:https://blog.csdn.net/qq_35946021/article/details/136452217
当A组件使用B组件的时候,A组件就是父组件,B组件就是子组件
ArkTS中的父子组件传值分为两种:父子组件对值的双向绑定,父组件对子组件单向传值
官方文档描述如下
组件状态管理装饰器用来管理组件中的状态,它们分别是:@State、@Prop、@Link。
@State装饰的变量是组件内部的状态数据,当这些状态数据被修改时,将会调用所在组件的build方法进行UI刷新。
官方文档:https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V2/arkts-state-0000001474017162-V2
@Prop与@State有相同的语义,但初始化方式不同。@Prop装饰的变量必须使用其父组件提供的@State变量进行初始化,允许组件内部修改@Prop变量,但更改不会通知给父组件,即@Prop属于单向数据绑定。
官方文档:https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V2/arkts-prop-0000001473537702-V2
@Link装饰的变量可以和父组件的@State变量建立双向数据绑定,需要注意的是:@Link变量不能在组件内部进行初始化。
官方文档:https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V2/arkts-link-0000001524297305-V2
代码示例
父组件
import {TitleComponent} from "../view/TitleComponent"
import {ButtonComponent} from "../view/ButtonComponent"
@Entry
@Component
struct Index {
@State text: string = 'World'
build() {
Row() {
Column() {
TitleComponent({message: this.text})
ButtonComponent({content: $text})
}
.width('100%')
}
.height('100%')
}
}文本子组件
@Component
export struct TitleComponent {
@Prop message: string
build() {
Row() {
Text("Hello, " + this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
}
}
}按钮子组件
@Component
export struct ButtonComponent {
@Link content: string
build() {
Row() {
Button("这是个按钮")
.height(80)
.width(200)
.margin(10)
.onClick(() => {
this.content = "mahe666"
})
}
}
}