从嵌套子屏幕访问父堆栈导航器的导航对象

Lee*_*fin 6 react-native react-navigation react-navigation-v5

我在我的react-native项目中使用React Navigation v5。

我有一个嵌套的堆栈导航器。

父堆栈导航器MyParentFlow有一个托管另一个堆栈导航器的屏幕组件:

const MyParentFlow = ({route, navigation}) => {

   const MyStack = createStackNavigator();

  return (
    <MyStack.Navigator
       initialRouteName={...}
       ...>
       {/*HERE is the nested children stack navigator*/}
       <MyStack.Screen
         name={FLOWS.MyChildrenFlow}
         component={MyChildrenFlow}
       />
       <MyStack.Screen .../>
       ...
    </MyStack.Navigator>
)
}
Run Code Online (Sandbox Code Playgroud)

我的嵌套堆栈导航器MyChildrenFlow

const MyChildrenFlow = ({route, navigation}) => {

   const MyStack = createStackNavigator();


  return (
    <MyStack.Navigator
       initialRouteName={...}
       ...>
       {/*HERE is a child screen in the nested navigator*/}
       <MyStack.Screen 
         name="MyChildScreen"
         component={MyChildScreen}
       />
       <MyStack.Screen .../>
       ...
    </MyStack.Navigator>
)
}
Run Code Online (Sandbox Code Playgroud)

在嵌套堆栈导航器托管的子屏幕中:

const MyChildScreen =({navigation})=> {
    /* I need to set options for the header of the parent's navigation */
    navigation.setOptions({
    headerRight: () => (
      ...
      />
    ),
  });

}
Run Code Online (Sandbox Code Playgroud)

在嵌套堆栈导航器托管的子屏幕中,我需要为父导航器设置navigation标题via。我的上面的代码不起作用,因为该navigation对象是嵌套堆栈导航器的,而不是父对象的。

我的问题是如何在嵌套子屏幕中访问父级导航器并为其设置导航选项?

sat*_*164 0

您可以通过以下方式访问它dangerouslyGetParent()

const parent = navigation.dangerouslyGetParent();
Run Code Online (Sandbox Code Playgroud)

https://reactnavigation.org/docs/navigation-prop/#dangerouslygetparent