如何访问 Stack Navigator 的 screenOptions 属性中的导航属性?

问题描述 投票:0回答:3

我想使用堆栈导航器中的通用标题按钮导航到特定屏幕。

 <NavigationContainer>
  <RootStack.Navigator 
    mode="modal"
    screenOptions={{
      headerTitleAlign: 'center',
      headerTitle: () => <SpreeLogo />,
      headerRight: (props) => <MaterialIcons style={{
        marginHorizontal: 10,
      }}
      onPress={() => console.log(props)}
      name="clear" size={28} color="black" />
    }}
  >

在标题右侧图标中,我想访问导航道具。我尝试过控制台记录道具,但没有道具作为导航。如何访问它?

reactjs react-native react-navigation
3个回答
9
投票

根据文档,您可以向 screenOptions 提供一个函数,如下所示,这将使您可以访问导航,并且从那里您应该能够跳转到任何屏幕

<NavigationContainer>
  <RootStack.Navigator 
    mode="modal"
    screenOptions={({ route, navigation }) => ({
      headerTitleAlign: 'center',
      headerTitle: () => <SpreeLogo />,
      headerRight: (props) => <MaterialIcons style={{
        marginHorizontal: 10,
      }}
      onPress={() => console.log(route, navigation)}
      name="clear" size={28} color="black" />
    })}
  >...

在此处阅读文档 https://reactnavigation.org/docs/stack-navigator 并搜索 screenOptions。

祝你好运


1
投票

在 React Navigation V6 中,你可以为选项提供一个函数

<Stack.Screen
    name="Screen"
    component={Screen}
    options={({ route, navigation }) => ({
      headerTitleAlign: "center",
      headerLeft: () => (
        <Icon
          name="arrow-back"
          onPress={() => navigation.goBack()}
          color="#fff"
          size={25}
        />
      ),

    })}
  />

0
投票

useNavigation 钩子

在根导航器中,可以使用v6.x React导航文档中记录的

useNavigation
钩子访问Navigation属性。

useNavigation 是一个可以访问导航对象的钩子。当您无法将导航道具直接传递到组件中,或者不想在深度嵌套的子组件的情况下传递它时,它非常有用。

useNavigation() 返回其所在屏幕的导航属性。

React Navigation 文档中的示例:

import * as React from 'react'; import { Button } from 'react-native'; import { useNavigation } from '@react-navigation/native'; function MyBackButton() { const navigation = useNavigation(); return ( <Button title="Back" onPress={() => { navigation.goBack(); }} /> ); }

使用OP代码的示例:

export function MyScreen() { //Hook to access the navigation prop of the parent screen anywhere. // @returns — Navigation prop of the parent screen. const navigation = useNavigation(); return( <NavigationContainer> <RootStack.Navigator mode="modal" screenOptions={{ headerTitleAlign: 'center', headerTitle: () => <SpreeLogo />, headerRight: (props) => <MaterialIcons style={{ marginHorizontal: 10, }} onPress={() => navigation.navigate('Somewhere') } name="clear" size={28} color="black" /> }} ) }

© www.soinside.com 2019 - 2024. All rights reserved.