整体上来看,首先需要使用Navigation组件构建路由导航的根视图容器,然后使用NavDestination构建子页面。在子页面中,将公共组件抽离,并利用queryNavDestinationInfo方法查询组件所属的页面,进行动态调整。
// 根容器 Navigation(this.navPathStack) { Button('跳转第一个页面').onClick(() => { this.navPathStack.pushPath({ name: 'one' }); }); Button('跳转第二个页面').onClick(() => { this.navPathStack.pushPath({ name: 'two' }); }); }.navDestination(this.myDestination);
@Component struct One { @Consume('navPathStack') navPathStack: NavPathStack; build() { NavDestination() { Text('第一个页面'); Common(); }; } } @Component struct Two { @Consume('navPathStack') navPathStack: NavPathStack; build() { NavDestination() { Text('第二个页面'); Common(); }; } }
// 公共组件 @Component struct Common { navDesInfo: uiObserver.NavDestinationInfo | undefined; aboutToAppear(): void { this.navDesInfo = this.queryNavDestinationInfo(); } build() { Column() { Text('这里是公共的组件'); Text("所属页面Name: " + this.navDesInfo?.name); }.width(200) .height(200) .border({ width: 5 }) // 根据NavDestinationInfo动态调整样式 .backgroundColor(this.navDesInfo?.name == 'one' ? Color.Blue : Color.Red); } }
完整示例参考如下:
import { uiObserver } from '@kit.ArkUI'; @Component @Entry struct DynamicallyAdjustPublicComponents { @Provide('navPathStack') navPathStack: NavPathStack = new NavPathStack(); @Builder myDestination(name: string) { if (name == 'one') { One(); } else if (name == 'two') { Two(); } } build() { // 根容器 Navigation(this.navPathStack) { Button('跳转第一个页面').onClick(() => { this.navPathStack.pushPath({ name: 'one' }); }); Button('跳转第二个页面').onClick(() => { this.navPathStack.pushPath({ name: 'two' }); }); }.navDestination(this.myDestination); } } @Component struct One { @Consume('navPathStack') navPathStack: NavPathStack; build() { NavDestination() { Text('第一个页面'); Common(); }; } } @Component struct Two { @Consume('navPathStack') navPathStack: NavPathStack; build() { NavDestination() { Text('第二个页面'); Common(); }; } } // 公共组件 @Component struct Common { navDesInfo: uiObserver.NavDestinationInfo | undefined; aboutToAppear(): void { this.navDesInfo = this.queryNavDestinationInfo(); } build() { Column() { Text('这里是公共的组件'); Text("所属页面Name: " + this.navDesInfo?.name); }.width(200) .height(200) .border({ width: 5 }) // 根据NavDestinationInfo动态调整样式 .backgroundColor(this.navDesInfo?.name == 'one' ? Color.Blue : Color.Red); } }