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

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

HarmonyOS
2024-05-26 15:39:40
865浏览
收藏 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 
    }) 
  } 
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.

实现效果

分享
微博
QQ
微信
回复
2024-05-27 20:43:16


相关问题
组件如何孙子组件进行状态同步
3870浏览 • 1回复 待解决
组件调用组件的方法
2222浏览 • 1回复 待解决
HarmonyOS 组件超出组件布局
838浏览 • 1回复 待解决
HarmonyOS 组件超出组件宽度
835浏览 • 1回复 待解决
HarmonyOS 组件调用组件方法
879浏览 • 1回复 待解决
组件组件传递函数
988浏览 • 1回复 待解决
组件调用组件里的方法
1118浏览 • 1回复 待解决
HarmonyOS 组件超过组件的范围
794浏览 • 1回复 待解决
HarmonyOS 组件调用组件的方法demo
845浏览 • 1回复 待解决
设置组件的宽度不超出组件
1299浏览 • 1回复 待解决
HarmonyOS 组件怎么调用组件的方法
1211浏览 • 1回复 待解决
组件的事件可以传到组件
1447浏览 • 1回复 待解决
组件溢出容器问题
2038浏览 • 1回复 待解决
如何设置组件组件宽度变化
3018浏览 • 1回复 待解决
组件事件能否到传递组件
3080浏览 • 1回复 待解决