子组件使用@Link修饰成员变量时,如何通过父组件传值

子组件使用@Link修饰成员变量时,如何通过父组件传值

HarmonyOS
2024-02-20 09:36:21
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
hz3000

@Link子组件从父组件初始化@State的语法为Comp({ aLink: this.aState })或Comp({aLink: $aState})。

@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; 
        }) 
    } 
  } 
}

参考链接

@Link装饰器

分享
微博
QQ
微信
回复
2024-02-20 19:19:26
相关问题
组件组件使用@Link双向同步
402浏览 • 1回复 待解决
OpenHarmony 使用WEB组件问题
2070浏览 • 1回复 待解决
组件调用组件的方法
542浏览 • 1回复 待解决
如何设置组件组件宽度变化
821浏览 • 1回复 待解决
组件溢出容器问题
566浏览 • 1回复 待解决
组件如何处理组件内点击事件
1505浏览 • 1回复 待解决
组件的事件可以传到组件
38浏览 • 1回复 待解决
设置组件的宽度不超出组件
25浏览 • 1回复 待解决
组件事件能否到传递组件
1111浏览 • 1回复 待解决
arkts父子组件组件怎么通信啊?
3612浏览 • 1回复 待解决
自定义组件和绑定
455浏览 • 1回复 待解决