Я вроде как новичок в react-native
и сейчас пытаюсь добавить stack-navigator
в свое приложение:
// import React from 'react';
import {Text, View, AppRegistry} from 'react-native';
import {createAppContainer} from 'react-navigation';
import {createStackNavigator} from 'react-navigation-stack';
// class HomeScreen extends React.Component {
// static navigationOptions = {
// title: 'Welcome',
// };
// render() {
// return (
// <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
// <Text>Home Screen</Text>
// </View>
// );
// }
// }
const MainNavigator = createStackNavigator({
Home: {screen: HomeScreen}
}, {
initialRouteName: 'Home'
})
const NavigationApp = createAppContainer(MainNavigator);
AppRegistry.registerComponent('ReactNativeApp', () => NavigationApp)
export default NavigationApp
Если я раскомментирую закомментированный код в приведенном выше примере, все будет работатьХорошо, теперь я пытаюсь переместить компонент HomeScreen
в его собственный файл, поэтому я попробовал это:
HomeScreen.js
class HomeScreen extends React.Component {
static navigationOptions = {
title: 'Welcome',
};
render() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Home Screen</Text>
</View>
);
}
}
index.js
import HomeScreen from './components'
import {AppRegistry} from 'react-native';
import {createAppContainer} from 'react-navigation';
import {createStackNavigator} from 'react-navigation-stack';
const MainNavigator = createStackNavigator({
Home: {screen: HomeScreen}
}, {
initialRouteName: 'Home'
})
const NavigationApp = createAppContainer(MainNavigator);
AppRegistry.registerComponent('ReactNativeApp', () => NavigationApp)
export default NavigationApp
Но я продолжаю получать эту ошибку:
error: bundling failed: Error: Unable to resolve module `./components` from `index.js`:
None of these files exist:
* components(.native|.ios.js|.native.js|.js|.ios.json|.native.json|.json|.ios.ts|.native.ts|.ts|.ios.tsx|.native.tsx|.tsx)
* components/index(.native|.ios.js|.native.js|.js|.ios.json|.native.json|.json|.ios.ts|.native.ts|.ts|.ios.tsx|.native.tsx|.tsx)
at ModuleResolver.resolveDependency (/Users/myuser/git/POC/ReactNativeApp/ReactNativeApp/node_modules/metro/src/node-haste/DependencyGraph/ModuleResolution.js:163:15)
at ResolutionRequest.resolveDependency (/Users/myuser/git/POC/ReactNativeApp/ReactNativeApp/node_modules/metro/src/node-haste/DependencyGraph/ResolutionRequest.js:52:18)
at DependencyGraph.resolveDependency (/Users/myuser/git/POC/ReactNativeApp/ReactNativeApp/node_modules/metro/src/node-haste/DependencyGraph.js:282:16)
at Object.resolve (/Users/myuser/git/POC/ReactNativeApp/ReactNativeApp/node_modules/metro/src/lib/transformHelpers.js:267:42)
at /Users/myuser/git/POC/ReactNativeApp/ReactNativeApp/node_modules/metro/src/DeltaBundler/traverseDependencies.js:426:31
at Array.map (<anonymous>)
at resolveDependencies (/Users/myuser/git/POC/ReactNativeApp/ReactNativeApp/node_modules/metro/src/DeltaBundler/traverseDependencies.js:423:18)
at /Users/myuser/git/POC/ReactNativeApp/ReactNativeApp/node_modules/metro/src/DeltaBundler/traverseDependencies.js:275:33
at Generator.next (<anonymous>)
at asyncGeneratorStep (/Users/myuser/git/POC/ReactNativeApp/ReactNativeApp/node_modules/metro/src/DeltaBundler/traverseDependencies.js:87:24)
В прошлом я мог импортировать их так же, как и я, нопочему-то react-navigation
вызывает у меня проблемы с этим.
У меня есть следующая структура папок:
/
index.js
components/
HomeScreen.js
Я видел похожие вопросы, но все они были связаны со сторонними компонентамииз react
но не из тех, что сделаны самим собой.
Я пытался npm start --reset-cache
, как предложено в этом ответе
Я использую эти версии, если это имеет значение.
react-native-cli: 2.0.1
react-native: 0.61.2
Какисправить эту ошибку?
После выполнения предложенного @Vencovsky решения (с расширением .js
и без него):
import HomeScreen from './components/HomeScreen.js'
Я получаю эту новую ошибку:
The component for route 'Home' must be a React component. For example:
import MyScreen from './MyScreen';
...
Home: MyScreen,
}
You can also use a navigator:
import MyNavigator from './MyNavigator';
...
Home: MyNavigator,
}
То, как я называю это приложение React, происходит через мост Swift:
import Foundation
import UIKit
import React
class ButtonController: UIViewController {
@IBOutlet weak var button: UIButton!
@IBAction func buttonClicked(_ sender: Any) {
if let jsBundleLocation = URL(string: "http://X.X.X.X:8081/index.bundle?platform=ios") {
//The data is used as initialProperties to React Native App.
let data:NSDictionary = ["onNavigationStateChange": "{handleNavigationChange}",
"uriPrefix":"/app"]; //We can use this parameter to pass the data to the React native App from the Native App.
//The RCTRootView is a native view used to host React-managed views within the app. Can be used just like any ordinary UIView.
let rootView = RCTRootView(
bundleURL: jsBundleLocation,
moduleName: "ReactNativeApp",
initialProperties: data as [NSObject : AnyObject],
launchOptions: nil)
let viewController = UIViewController()
viewController.view = rootView
self.present(viewController, animated: true, completion: nil)
}
}
}