开发者问题收集

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

2020-08-12
6884

export default function App ({navigation})

有一个函数以 <Stack.Navigator> 开头并包含它。

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

TypeError: undefined is not an object evaluating react navigation

我收到错误。我的英语不是很好。请帮助我解决这个问题。现在我正在向您添加示例代码。

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>
    </>
  );
}
3个回答

您可以将导航或路由属性传递到 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>
                  )
         })} />
Mudit Gulgulia
2020-08-12

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

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

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

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

const LinkButton = ({ to, action, children, ...rest }) => {
  const { onPress, ...props } = useLinkProps({ to, action });
Nqobile Ndlovu
2020-08-12