为什么App.js中未定义React Native App.js导航?

时间:2020-08-12 09:34:56

标签: javascript reactjs react-native expo

导出默认功能应用程序({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>
    </>
  );
}

4 个答案:

答案 0 :(得分:1)

您可以像这样将导航或溃败道具传递到堆栈中的选项中。

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>
                  )
         })} />

答案 1 :(得分:0)

首先,我认为这里的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>
)})} />

答案 2 :(得分:0)

您应该使用useLinkProps来解决此问题:

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

这是有关如何编写使用该代码的示例:

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

答案 3 :(得分:0)

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

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