简体   繁体   中英

Navigating between screens in different files

I have been running into an issue with navigating between screens in different files; I am assuming this is due to improperly exporting the functional components from one file to another. I created a snack for it: https://snack.expo.dev/@figbar/exportingbetweenscreens , and pasted the code in that below. Essentially, if 'DetailsScreen' is in app.js, the project becomes the sample navigation project, and works properly, however, when it is in this new file, the details screen is blank when navigated to.

App.js:

import * as React from 'react';
import { Button, View, Text } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import {DetailsScreen} from './other';

function HomeScreen({ navigation }) {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>Home Screen</Text>
      <Button
        title="Go to Details"
        onPress={() => navigation.navigate('Details')}
      />
    </View>
  );
}

const Stack = createStackNavigator();

function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator initialRouteName="Home">
        <Stack.Screen name="Home" component={HomeScreen} />
        <Stack.Screen name="Details" component={DetailsScreen} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

export default App;

other.js:

import * as React from 'react';
import { Button, View, Text } from 'react-native';

function DetailsScreen() {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>Details Screen</Text>
    </View>
  );
}
export default DetailsScreen;

DetailsScreen was exported as default, so it should be imported like this:

import DetailsScreen from './other';

and not this:

import {DetailsScreen} from './other';

Remove the curly braces and you will be good to go. Or alternatively, don't export DetailsScreen as default

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM