HarmonyOS @Provide/@Consume 跨组件通信

发布时间:2026/7/18 5:27:00
HarmonyOS @Provide/@Consume 跨组件通信 适用版本HarmonyOS 6.1API 12及以上验证环境Pura 90 Pro 模拟器HarmonyOS 6.1.1API 24关键概念Provide、Consume、跨层级状态共享、主题系统前言Prop和Link适合直接父子通信但当状态需要跨越多个层级祖父→孙子时层层传递Prop十分繁琐。Provide/Consume解决了这个问题祖先组件“提供“状态任意后代组件“消费“无需中间层显式传递。一、基本用法// 祖先组件根组件 Entry Component struct AppRoot { Provide themeColor: string #0066ff // 提供共享状态 Provide themeName: string 蓝色主题 build() { Column() { MiddleLayer() // 中间层 } } switchTheme(): void { this.themeColor #07C160 // 修改 Provide → 所有 Consume 自动刷新 this.themeName 绿色主题 } } // 中间层无需关心 themeColor不用传 Prop Component struct MiddleLayer { build() { Column() { ThemeDisplay() // 深层子组件 } } } // 深层子组件直接消费 Component struct ThemeDisplay { Consume themeColor: string // 变量名必须与 Provide 一致 Consume themeName: string build() { Row() { Text().width(40).height(40).borderRadius(20).backgroundColor(this.themeColor) Text(当前主题: ${this.themeName}) } } }二、Provide 别名当变量名可能冲突时用字符串指定别名// 祖先 Provide(primaryColor) mainColor: string #0066ff // 后代用别名消费本地变量名可以不同 Consume(primaryColor) localColor: string三、子组件中的 Consume 也可以修改状态Consume和Link一样是双向的——子组件修改Consume变量会同步回Provide所在的祖先组件Component struct ThemeButton { Consume themeColor: string // 双向 label: string onTap: () void () {} build() { Button(this.label) .backgroundColor(this.themeColor) // 响应主题色变化 .onClick(() { this.onTap() }) } }四、与 Prop/Link 对比特性PropLinkProvide/Consume数据流父→子单向父↔子双向祖先↔任意后代双向跨层级❌ 需逐层传递❌ 需逐层传递✅ 直接跨层中间层需传递需传递无需关心适用场景直接父子展示直接父子双向主题、语言、权限等全局状态五、实战主题切换系统Entry Component struct AppRoot { Provide themeColor: string #0066ff Provide themeName: string 蓝色主题 Provide clickCount: number 0 private themes: string[][] [ [#0066ff, 蓝色主题], [#07C160, 绿色主题], [#e74c3c, 红色主题], [#9b59b6, 紫色主题], ] private idx: number 0 switchTheme(): void { this.idx (this.idx 1) % this.themes.length this.themeColor this.themes[this.idx][0] this.themeName this.themes[this.idx][1] this.clickCount } build() { Column() { Button(切换主题).onClick(() { this.switchTheme() }) NavBar() // 导航栏自动刷新主题色 ContentArea() // 内容区自动刷新主题色 } } }模拟器运行截图初始状态蓝色主题切换主题后点击「切换主题」后根组件修改Provide themeColor所有Consume themeColor的子组件中间层预览条、深层子组件 ThemeDisplay同步刷新颜色。实测结果切换次数主题根/中间层/深层子组件颜色0蓝色主题#0066ff全部同步为蓝色1绿色主题#07C160全部同步为绿色2红色主题#e74c3c全部同步为红色3紫色主题#9b59b6全部同步为紫色常见问题QProvide 变量和 State 变量有什么区别AProvide在内部仍然是State额外的作用是“广播“给所有后代中的Consume。单纯的State不会向后代广播。Q两个 Provide 变量名相同会冲突吗A如果组件树中存在嵌套的同名Provide内层的Provide会遮蔽外层Consume会找到最近的祖先Provide。通常应避免同名冲突使用别名区分。QConsume 必须有初始值吗A不需要初始值与Link一样ArkUI 运行时会在组件挂载时从祖先的Provide注入值。如果找不到对应的Provide运行时会报错。上一篇状态管理State/Prop/Link/Watch下一篇动画与过渡效果