【问题标题】:How to Access the navigation prop from any component?如何从任何组件访问导航道具?
【发布时间】:2021-06-10 17:57:04
【问题描述】:

我在不同的 stackoverflow 帖子以及来自https://reactnavigation.org/docs/connecting-navigation-prop/ 的原始文档中尝试了多种方法 但仍然未能解决我的问题。

我有一个登录屏幕,在我导航到主屏幕后, 我想从主屏幕导航到另一个屏幕,但导航道具未定义。

尝试按照文档进行操作,但仍然失败。

请帮忙,非常感谢。

我已经导入了我的 App.js、HomePage.js(我想导航到另一个屏幕但失败的那个)

目前我拥有的代码是基于文档的,但在单击按钮时无效。

import * as RootNavigation from '../config/RootNavigation';
const HomePage = () => {

    const onLogOut = () => {
        alert("Logged out")
        firebase.auth().signOut();
    }

    const inventoryOnPress = () => {
        RootNavigation.navigate('InventoryScreen')
    }


    return(
        <View>
                <CardComponent 
                style={styles.cardBackground} 
                title="Inventory"
                onPress={inventoryOnPress}/>
        </View>
    );
}

export default HomePage;

   
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import { navigationRef } from './src/config/RootNavigation';

const Stack = createStackNavigator();
function NavStack() {

  const [initialPage,setInitialPage] = useState('LoginScreen');
  return(
    <Stack.Navigator
    initialRouteName={initialPage}
    screenOptions={{
      headerTitleAlign:'center',
      headerStyle: {
        backgroundColor: '#621FF7'
      }
    }}
    >
      <Stack.Screen 
              name="LoginScreen"
              component={LoginPage}
            />
            <Stack.Screen 
              name="HomeScreen"
              component={HomePage} 
              headerLeft={null}
            />
            <Stack.Screen 
              name="SignUpScreen"
              component={SignUpPage}
            />
            <Stack.Screen 
              name="InventoryScreen"
              component={InventoryPage}
            />

    </Stack.Navigator>
  )
}


function App() {
      return (
        <NavigationContainer ref={navigationRef}>
           <NavStack />
        </NavigationContainer>
      );
    }
}

// RootNavigation.js

import * as React from 'react';

export const navigationRef = React.createRef();

export function navigate(name, params) {
  navigationRef.current?.navigate(name, params);
}

// add other navigation functions that you need and export them

【问题讨论】:

  • 请不要发布墙代码。创建一个重现您遇到的问题的minimal 示例。你在使用 React 导航时遇到了问题。您不需要六个或更多包含问题中样式的组件,这使得在创建最小再现案例的过程中阅读变得困难且频繁(例如您需要提交错误或 github 问题),您将解决你自己的问题。
  • 对不起,我已经编辑了帖子中的代码。

标签: javascript react-native react-native-navigation


【解决方案1】:

请不要在 SO 上发布 firebase 或任何其他 API 密钥。

您在此处处理导航(身份验证)的方式存在一些问题。 请阅读文档Auth Flow 以获得详细答案。一个问题是,当用户登录时,您只返回 HomeScreen 并且没有返回 NavigationContainer,这是您无法访问 HomePage 中的导航属性的原因之一。

所以基本上在你的 App() fn 中你可以返回类似这样的东西

<NavigationContainer>
<Stack.Navigator>
isSignedIn ? (
  <>
    <Stack.Screen name="Home" component={HomeScreen} />
    <Stack.Screen name="Profile" component={ProfileScreen} />
    <Stack.Screen name="Settings" component={SettingsScreen} />
  </>
) : (
  <>
    <Stack.Screen name="SignIn" component={SignInScreen} />
    <Stack.Screen name="SignUpScreen" component={SignUpPage} />
  </>
)
</Stack.Navigator>
</NavigationContainer>

现在要在 HomeScreen 中获取导航道具,如果您更喜欢钩子,可以使用 useNavigation Hook。

import { useNavigation } from '@react-navigation/native';

const HomePage = () => {
const navigation = useNavigation();

  return (
    <Button
      title="Navigate To Profile"
      onPress={() => navigation.navigate("Profile")}
    />
  );
}

【讨论】:

  • NavigationContainer 从 OP 共享的代码中返回。
  • @Rohit OP 编辑​​了代码,以尽量减少复制。所以他所有的身份验证逻辑都被删除了。
【解决方案2】:

navigation 属性可用于 NavigationContainer 中包含的每个单独的屏幕。
您可以按如下方式访问它

const inventoryOnPress = () => {
       props.navigation.navigate('InventoryScreen')
    }

请参阅this 文章以获取更多详细信息。

更新

如果您无法使用对NavigationContainer 的引用获得navigation 属性,则这意味着您的组件尚未呈现并且已对其应用了一些操作。
因此,为了避免这种情况,请使用 navigationRef.current.getRootState() 来查看它是否返回一个有效对象并进行导航。

【讨论】:

    猜你喜欢
    • 2019-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-25
    • 2020-10-12
    相关资源
    最近更新 更多