2017-08-02 27 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)查看實際獲取的內容。

相關問題