OpenHarmony开发者论坛
标题:
子组件使用@Link修饰成员变量时,如何通过父组件传值
[打印本页]
作者:
edice
时间:
2023-11-3 15:57
标题:
子组件使用@Link修饰成员变量时,如何通过父组件传值
[md]【问题描述】
子组件变量使用@Link修饰,父组件中通过键值对的方式传值,居然报错了

【运行环境】
硬件:RK3568
ROM版本:Openharmony 3.2 Beta5
DevEvoStudio版本:
SDK版本:API 9
[/md]
作者:
westinyang
时间:
2023-11-4 10:38
[md]value: $value
[/md]
作者:
清风明月
时间:
2023-11-9 09:42
子组件使用@Link接受父组件的值时,需要使用'$'建立变量之间的引用关系。才能实现同步。
代码示例
@Link语义是从'′操作符引出,即′操作符引出,即isPlaying是this.isPlaying内部状态的双向数据绑定。当单击子组件PlayButton中的按钮时,@Link变量更改,PlayButton与父组件中的Text和Button将同时进行刷新,同样地,当点击父组件中的Button修改this.isPlaying时,子组件PlayButton与父组件中的Text和Button也将同时刷新。
1.在父组件使用@State装饰器,传递数据使用$符创建引用。
@Entry
@Component
struct Player {
@State isPlaying: boolean = false
build() {
Column() {
PlayButton({ buttonPlaying: $isPlaying })
Text(`Player is ${this.isPlaying ? '' : 'not'} playing`).fontSize(18)
Button('Parent:' + this.isPlaying)
.margin(15)
.onClick(() => {
this.isPlaying = !this.isPlaying
})
}
}
}
复制代码
2.在子组件使用@Link接受数据。
@Component
struct PlayButton {
@Link buttonPlaying: boolean
build() {
Column() {
Button(this.buttonPlaying ? 'pause' : 'play')
.margin(20)
.onClick(() => {
this.buttonPlaying = !this.buttonPlaying
})
}
}
}
复制代码
欢迎光临 OpenHarmony开发者论坛 (https://forums.openharmony.cn/)
Powered by Discuz! X3.5