父子组件传值-@link- 可以互相传递

@Entry
@Component
struct Parent {
@State count: number = 1;

build() {
Column() {
Column({ space: 10 }) {
//父组件标题
Text('父组件').textStyle()
//父组件计数器
Row({ space: 10 }) {
Text('@State').textStyle()
Counter() {
Text(this.count.toString()).textStyle()
}
.onInc(() => this.count++)
.onDec(() => this.count--)
}

//子组件
Child({ count: $count })
}
.containerStyle(Color.White)
}
.height('100%')
.width('100%')
.justifyContent(FlexAlign.Center)
.backgroundColor('#EFEFEF')
.padding(10)
}
}

@Component
struct Child {
@Link count: number;

build() {
Column({ space: 10 }) {
//子组件标题
Text('子组件').textStyle()
//子组件计数器
Row({ space: 10 }) {
Text('@Link').textStyle()
Counter() {
Text(this.count.toString()).textStyle()
}
.onInc(() => this.count++)
.onDec(() => this.count--)
}
}
.containerStyle('#CCE3CB')
}
}

@Extend(Text) function textStyle() {
.fontSize(25)
.fontWeight(FontWeight.Bold)
}

@Extend(Column) function containerStyle(color: ResourceColor) {
.width('100%')
.backgroundColor(color)
.padding(10)
.borderRadius(20)
}
posted @ 2025-03-16 13:22  13522679763-任国强  阅读(9)  评论(0)    收藏  举报