拆分React Navigation页面至独立文件时遇Component Exception求助
This error is super common when splitting React Navigation screens into separate files—9 times out of 10 it's an import/export mismatch between your App.js and the component files. Let's break down what's going wrong and how to fix it.
What's Causing the Error?
Your App.js uses named imports (import { Page1 } from './Page1'), which expect your components to be exported with a named export. But if you used a default export in Page1.js/Page2.js, React will import undefined for those components—exactly what the error is complaining about.
Step-by-Step Fixes
Option 1: Use Default Imports (Most Common)
If your Page1/Page2 components use a default export (like this):
// Page1.js import React from 'react'; import { View, Text } from 'react-native'; function Page1() { return ( <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}> <Text>Page 1</Text> </View> ); } export default Page1; // Default export
Update your App.js to use default imports (remove the curly braces):
import { NavigationContainer } from '@react-navigation/native'; import { createStackNavigator } from '@react-navigation/stack'; import React from 'react'; import Page1 from './Page1'; // No curly braces import Page2 from './Page2'; // No curly braces const Stack = createStackNavigator(); function App() { return ( <NavigationContainer> <Stack.Navigator> <Stack.Screen name="Page1" component={Page1} /> <Stack.Screen name="Page2" component={Page2} /> </Stack.Navigator> </NavigationContainer> ); } export default App;
Option 2: Use Named Exports
If you prefer named exports, make sure your component files export the component explicitly with a named export:
// Page1.js import React from 'react'; import { View, Text } from 'react-native'; export function Page1() { // Named export return ( <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}> <Text>Page 1</Text> </View> ); }
In this case, your original App.js imports (with curly braces) are correct—just double-check that the exported name matches exactly (case-sensitive!).
Quick Checks to Rule Out Other Issues
- Filename Case: On macOS/Linux, filenames are case-sensitive. Make sure you're importing from
./Page1.jsnot./page1.jsif your file is namedPage1.js. - Missing Export: Double-check that you didn't forget the
exportkeyword in your component files. - Path Accuracy: Ensure the relative path to Page1/Page2 is correct (e.g., if they're in a
screensfolder, use./screens/Page1instead of./Page1).
内容的提问来源于stack exchange,提问作者Muhammad Hamza

