基本上我想将react-native代码拆分为几个js文件。我有我的主要' index.ios.js '文件。我将一些代码( MainComponent 类)移动到另一个文件:'。/ iOSCode / main.js'
如何将整个' ./ iOSCode / main.js '文件内容导入' index.ios.js '?
我试过了:
import { MainComponent as MainComponent } from './iOSCode/main.js';
and
import MainComponent from './iOSCode/main.js';
没有运气......
我收到错误:
Element type is invalid: expected a string (for built-in components) or class/function [...] but got: undefined
intantiateReactComponent.js:70
instantiateChild ReactChildReconciler.js:45
==========
编辑:
从@ Jagadish Upadhyay的建议开始,我错过了'./iOSCode/main.js'内的MainComponent类附近的 export 语句
代码:
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
ListView
} from 'react-native';
export class MainComponent extends Component {
render() {
return (
<Text> abc </Text>
);
}
}
答案 0 :(得分:4)
要分类,您需要添加导出语句并使用此导入格式:
import { MainComponent as MainComponent } from './iOSCode/main.js';
您还可以将样式移出到单独的文件中。
styles.js:
import {
StyleSheet
} from 'react-native';
const styles = StyleSheet.create({
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
});
module.exports = styles;
并在主js文件中使用此导入:
import * as styles from './styles.js';
请务必添加:&#39; module.exports = styles;&#39;