我的目标是从名为home.js的外部.js文件渲染主屏幕。该.js文件位于根项目目录下一个名为“ screens”的文件夹中的目录中。我在渲染该home.js文件中的内容时遇到了麻烦。如果我将代码从home.js文件移回至app.js文件,则可以正常工作。我正在尝试采用模块化方法,因为这是最佳实践,并且不希望将所有内容都填充到app.js文件中。我计划在不久的将来创建更多的屏幕,但是我想首先将基础知识笼罩其中。
app.js文件中的当前代码
// In App.js in a new project
import React from "react";
import { View, Text } from "react-native";
import { createStackNavigator, createAppContainer } from "react-navigation";
import HomeScreen from './screens/home.js';
/*
class DetailsScreen extends React.Component {
render() {
return (
<View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}>
<Text>Details Screen</Text>
</View>
);
}
}
*/
export default createAppContainer(AppNavigator);
const AppNavigator = createStackNavigator(
{
Home: HomeScreen,
//Details: DetailsScreen
},
{
initialRouteName: "Home"
}
);
home.js文件中的代码是
import React from "react";
import { View, Text } from "react-native";
class HomeScreen extends React.Component {
render() {
return (
<View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}>
<Text>Home Screen</Text>
</View>
);
}
}
编辑1: 我当前的错误是
undefined is not an object (evaluating 'Component.router')
createNavigationContainer
C:\Repos\demoProject\node_modules@react-navigation\native\src\createAppContainer.js:88:30
<unknown>
C:\Repos\demoProject\App.js:24:34
loadModuleImplementation
C:\Repos\demoProject\node_modules\metro\src\lib\polyfills\require.js:331:6
<unknown>
C:\Repos\demoProject\node_modules\expo\AppEntry.js:4
loadModuleImplementation
C:\Repos\demoProject\node_modules\metro\src\lib\polyfills\require.js:331:6
guardedLoadModule
C:\Repos\demoProject\node_modules\metro\src\lib\polyfills\require.js:197:45
global code
<unknown file>:0
答案 0 :(得分:3)
您不导出HomeScreen组件,可以通过在类定义的前面或下面添加export default
来实现。
export default class HomeScreen extends React.Component {
render() {
return (
<View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}>
<Text>Home Screen</Text>
</View>
);
}
}
或
class HomeScreen extends React.Component {
render() {
return (
<View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}>
<Text>Home Screen</Text>
</View>
);
}
}
export default HomeScreen
您还试图在实例化AppNavigator之前将其导出。您需要将导出内容移到下面。
const AppNavigator = createStackNavigator(
{
Home: HomeScreen,
//Details: DetailsScreen
},
{
initialRouteName: "Home"
}
);
export default createAppContainer(AppNavigator);