2017-08-02 24 views
1

我正尝试在React Native应用程序中使用Android和iOS的单个条目文件。使用单个条目文件进行反应原生应用程序

我按照一些教程,并结束了以下内容:

index.js

import React, { Component } from 'react'; 
import { Text } from 'react-native'; 

export default class Main extends Component { 
    render() { 
     return (
     <Text>Hello world! from both IOS and Android</Text> 
    ); 
    } 
} 

index.ios.js

import React from 'react'; 
import { AppRegistry } from 'react-native'; 
import {Main} from './index'; 


AppRegistry.registerComponent('Main',() => Main); 

我结束了以下错误:

Element type is invalid: expected a string(for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in.

如果我在导入语句中删除Main中的大括号,它会显示'...但是:object',所以我觉得这与我的导出/导入有关,但似乎没有任何效果。任何帮助,将不胜感激。

回答

1

要导出您Main成分为:

export default class Main extends Component { 

但进口为:

import {Main} from './index'; 

default export应该导入为:如果使用默认的出口

import Main from './index'; 

,你必须像这样导入。如果这不起作用,那么代码中必然存在另一个问题。

+0

感谢您的快速响应。如果我删除大括号,我有同样的错误,但它说'对象',而不是'未定义'。关于还有什么可能会导致问题的任何想法?如果需要,我可以发布其他相关代码。 – Brandon

+0

你可以粘贴整条信息吗? –

+0

好吧,我实际上(约两个小时后)才开始工作。我将index.js移动到不再位于与index.ios.js和index.android.js相同的目录中。我把它移到了一个子目录中,然后把import语句改成了从'./src/app'导入Main并开始工作。我不明白为什么? – Brandon

0

React Native尝试基于平台导入。例如,如果您在同一文件夹中有index.ios.jsindex.android.js,则React Native仅在为ios捆绑时绑定index.ios.js。当您从./index导入时,React Native可能会使用index.ios.js而不是index.js来循环路径,因为您是捆绑在一起的ios。

如果您足够好奇,可以尝试导入模块的内容,例如console.logconsole.log(Main)查看实际获取的内容。

相关问题