【问题标题】:Why is React Native App.js navigation undefined in App.js?为什么在 App.js 中未定义 React Native App.js 导航?
【发布时间】:2020-08-12 09:34:56
【问题描述】:

导出默认功能 App ({navigation})

有一个以开头并包含的函数。

但是当我想使用导航功能并在 onPress 中使用“navigation.navigate ('Lead')”时

TypeError:未定义不是评估反应导航的对象

我得到一个错误。我的英文不是很好。请在这个话题上帮助我。现在我将示例代码添加给您。

import * as React from 'react';
import { StyleSheet, AsyncStorage, Alert, View, Image, TouchableOpacity } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import { ApplicationProvider, Layout, Input, Button, Text, Spinner, IconRegistry, Icon } from '@ui-kitten/components';
import { EvaIconsPack } from '@ui-kitten/eva-icons';
import * as eva from '@eva-design/eva';
import LinkingConfiguration from './navigation/LinkingConfiguration';
import * as axios from 'axios';
import Base64 from './components/Base64';
import LeadScreen from './screens/LeadScreen';
import AddLeadScreen from './screens/AddLeadScreen';
import TabBarIcon from './components/TabBarIcon';
import HomeScreen from './screens/HomeScreen';
import CampaignsScreen from './screens/CampaignsScreen';
import MenuScreen from './screens/MenuScreen';

const Stack = createStackNavigator();

export default function App({ navigation }) {  
  const logout = async () => {
    await AsyncStorage.removeItem('token');    
    dispatch({ type: 'SIGN_OUT' });
  };
  
  return (    
    <>
      <IconRegistry icons={EvaIconsPack} />
      <ApplicationProvider {...eva} theme={eva.light}>        
          <Layout style={styles.container}>
            <AuthContext.Provider value={authContext}>
              <NavigationContainer linking={LinkingConfiguration}>
                <Stack.Navigator>
                  {state.isLoading ? (
                    // We haven't finished checking for the token yet
                    <Stack.Screen name="Splash" component={SplashScreen} options={{ headerShown: false }} /> 
                    ) : state.token == null ? (
                    // No token found, user isn't signed in
                    <>
                      <Stack.Screen name="Login" component={LoginScreen} options={{ title: 'Oturum Açın' }} />                      
                    </>
                    ) : (
                    // User is signed in
                    <>
                    <Stack.Screen name="User" component={UserScreen} options={{
                        headerStyle: { backgroundColor: '#e8a200' },
                        headerTintColor: 'white',
                        headerTitleStyle: { color: '#fff' },
                        headerRight: () => (
                          <TouchableOpacity activeOpacity={0.4} underlayColor='transparent' onPress={() => logout() } style={{ marginRight: 12 }}>
                            <Icon
                              style={styles.icon}
                              fill='#FFFFFF'
                              name='power-outline'
                            />
                          </TouchableOpacity>
                        )
                      }} />

                      <Stack.Screen name="Lead" component={LeadScreen} options={{
                        title: 'Müşteri Adayları',
                        headerStyle: { backgroundColor: '#e8a200' },
                        headerTintColor: 'white',
                        headerTitleStyle: { fontWeight: 'bold', color: '#fff' },
                        headerRight: () => (
                          <TouchableOpacity activeOpacity={0.4} underlayColor='transparent' onPress={ () => console.log(navigation) } style={{ marginRight: 12 }}>
                            <Icon
                              style={styles.icon}
                              fill='#FFFFFF'
                              name='plus-outline'
                            />
                          </TouchableOpacity>
                      )}} />

                      <Stack.Screen name="AddLead" component={AddLeadScreen} options={{ title: 'Müşteri Adayı Ekle' }} />
                    </>
                  )}              
                </Stack.Navigator>
              </NavigationContainer>
            </AuthContext.Provider>
        </Layout>
      </ApplicationProvider>
    </>
  );
}

【问题讨论】:

  • 可以分享更多示例代码吗?
  • 当然,我加了。

标签: javascript reactjs react-native expo


【解决方案1】:

您可以像这样将 navigation 或 rout 属性传递给 stack.screen 中的选项

options={({navigation})=>({
    'Your code here'
})}

我已经用你的代码为你编辑了它。

        <Stack.Screen name="Lead" component={LeadScreen}
         options={({ navigation }) => ({
             title: 'Müşteri Adayları',
             headerStyle: { backgroundColor: '#e8a200' },
             headerTintColor: 'white',
             headerTitleStyle: { fontWeight: 'bold', color: '#fff' },
             headerRight: () => (
                <TouchableOpacity activeOpacity={0.4} 
                   underlayColor='transparent' onPress={() => 
                   console.log(navigation)} style={{ marginRight: 12 }}>
                    <Icon
                       style={styles.icon}
                          fill='#FFFFFF'
                          name='plus-outline'
                      />
                  </TouchableOpacity>
                  )
         })} />

【讨论】:

    【解决方案2】:

    首先,我认为这里的navigation是不必要的,你可以删除它。

    export default function App({ navigation }) {  
    

    在您的屏幕组件中,即。 UserScreen,你可以这样使用导航

    function UserScreen({navigation}) {
      // ...some codes
      navigation.navigate('WHERE_TO_GO');
      // ...some other codes
    }
    

    您也可以使用导航而不将其传递给道具。

    首先你需要导入useNavigation

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

    然后,在你的组件中

    function UserScreen() {
      const nav = useNavigation();
      // ...some codes
      nav.navigate('WHERE_TO_GO');
      // ...some other codes
    }
    

    您可以在这里https://reactnavigation.org/docs/use-navigation/获取更多详细信息

    对于Lead屏幕的onPress功能,

    <Stack.Screen name="Lead" component={LeadScreen} options={({ navigation }) => ({
      title: 'Müşteri Adayları',
      headerStyle: { backgroundColor: '#e8a200' },
      headerTintColor: 'white',
      headerTitleStyle: { fontWeight: 'bold', color: '#fff' },
      headerRight: () => (
        <TouchableOpacity activeOpacity={0.4} underlayColor='transparent' onPress={ () => navigation.navigate('WHERE_TO_GO') } style={{ marginRight: 12 }}>
          <Icon
            style={styles.icon}
            fill='#FFFFFF'
            name='plus-outline'
          />
        </TouchableOpacity>
    )})} />
    

    【讨论】:

    • 但我必须在导出中使用它。它不是外部函数。请仔细检查代码。
    • 由于您似乎使用的是 React Navigation 5,您仍然可以使用导航而不通过 props 传递它。让我编辑代码。
    • 谢谢,我在等。
    • 抱歉,您仍然是通过外部函数执行此操作。我与 UserScreen 无关。我想在
    • 哦。抱歉,我仅以 UserScreen 为例。让我输入 onPress 的代码。
    【解决方案3】:

    你应该使用useLinkProps来解决这个问题:

    import { useLinkProps } from '@react-navigation/stack';
    

    这是一个关于如何编写使用它的代码的示例:

    const LinkButton = ({ to, action, children, ...rest }) => {
      const { onPress, ...props } = useLinkProps({ to, action });
    

    【讨论】:

    • 对不起,我的朋友,我想使用onPress中的导航变量。你能检查一下代码吗?
    • 请不要只发布代码作为答案,还要解释您的代码的作用以及它如何解决问题的问题。带有解释的答案通常更有帮助,质量更高,更有可能吸引投票。
    • @MarkRotteveel 感谢您的解释,一定会牢记这一点。努力争取那些赞成票。大声笑...
    【解决方案4】:

    我已经尝试了所有方法,但这对我有用。 在你的 app.js 中创建一个函数并传递 props,然后使用 props.navigation 访问,如下所示。

    function CustomDrawerContent**(props)** {
    .....
        
      logOut = () => {
        AsyncStorage.clear(); 
        **props.navigation.navigate("Login");**
      };
    .....
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-02-01
      • 2021-04-04
      • 1970-01-01
      • 2019-04-16
      • 2021-09-16
      • 2020-03-07
      • 1970-01-01
      相关资源
      最近更新 更多