父组件与子组件使用@Link双向同步

构建父组件KRScroll,在父组件中配置变量 contentWidth和contentHeight。将父组件作为入参传入后,取其中的contentWidth及contentHeight,并传入子组件的自定义组件中使用。 希望对父子组件中的变量进行关联。

HarmonyOS
2024-05-26 15:39:40
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
put_get

使用的核心API

  •  @LocalStorageLink
  •  LocalStorage

核心代码解释

@Builder 
function render() { 
  childComponent() 
} 
 
// 构造LocalStorage实例 
let para: Record<string, number> = { 
  'childWidth': 0, 
  'childHeight': 0 
}; 
let storage: LocalStorage = new LocalStorage(para); 
 
@Entry 
@Component 
struct Page240126091206035 { 
  @State message: string = 'Hello World'; 
  @LocalStorageLink("childWidth") childWidth: Length = 0 
  @LocalStorageLink("childHeight") childHeight: Length = 0 
 
  aboutToAppear(): void { 
    this.childWidth = "100%" 
    this.childHeight = 400 
  } 
 
  build() { 
    Row() { 
      Column() { 
        render() 
      } 
      .width('100%') 
    } 
    .height('100%') 
  } 
} 
 
@Component 
struct childComponent { 
  @LocalStorageLink("childWidth") childWidth: Length = 0 
  @LocalStorageLink("childHeight") childHeight: Length = 0 
 
  build() { 
    Column() { 
    } 
    .backgroundColor(Color.Pink) 
    .width(this.childWidth) 
    .height(this.childWidth) 
    .onClick(() => { 
      this.childWidth = 200 
      this.childHeight = 200 
    }) 
    .onAreaChange((old: Area, newValue: Area) => { 
      this.childWidth = newValue.width 
      this.childHeight = newValue.height 
    }) 
  } 
}

实现效果

分享
微博
QQ
微信
回复
2024-05-27 20:43:16
相关问题
组件如何孙子组件进行状态同步
796浏览 • 1回复 待解决
组件调用组件的方法
409浏览 • 1回复 待解决
组件溢出容器问题
452浏览 • 1回复 待解决
组件事件能否到传递组件
865浏览 • 1回复 待解决
如何设置组件组件宽度变化
551浏览 • 1回复 待解决
组件中如何处理组件内点击事件
1068浏览 • 1回复 待解决
弹窗组件调用组件函数传递
378浏览 • 1回复 待解决
如何选择Navigation 组件 Tabs 组件
698浏览 • 1回复 待解决
循环显示包含图片的组件
437浏览 • 1回复 待解决