2016-06-22 58 views
1

我是新來做出反應,並且我遇到了多個組件的問題。ReactJs - 多個組件 - 錯誤:未捕獲ReferenceError:需求未定義

這是錯誤我得到未捕獲的ReferenceError:要求沒有定義,我使用

代碼。

的Index.html

<!DOCTYPE html> 
<html lang="en"> 
<head> 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.js"></script> 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.js"></script> 
    <script src="https://fbcdn-dragon-a.akamaihd.net/hphotos-ak-xtf1/t39.3284-6/11057100_835863049837306_1087123501_n.js"></script> 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.34/browser.min.js"></script> 
    <meta charset="UTF-8"> 
    <title></title> 
</head> 
<body> 
    <div id="app"></div> 
    <script type="text/babel" src="js/layout.js"></script> 
</body> 
</html> 

layout.js

import React from "react"; 
import ReactDOM from "react-dom"; 

import Header from "./header"; 

class Layout extends React.Component { 
    render() { 
     return(
     <div> 
      <Header/> 
     </div> 
    ); 
    } 
} 

const app = document.getElementById("app"); 
ReactDOM.render(<Layout/>, app); 

而且header.js

import React from "react"; 
import ReactDOM from "react-dom"; 

export default class Header extends React.Component { 
    render() { 
     return(
      <h1>Hello header</h1> 
    ); 
    } 
} 

回答

3

Babel只處理transpilation部分(即ES2015和JSX語法轉換成有效ES5)。但是您仍然需要使用捆綁器(webpack,browserify)或模塊加載器(systemjs或jspm)來加載模塊。

這裏是一個使用SystemJS的例子。 Example

配置systemjs裝載機從CDN

System.config({ 
    transpiler: 'babel', 
    baseURL: '', 
    map: { 
     babel: 'https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.34/browser.min.js', 
     react: 'https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.js', 
     'react-dom': 'https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.js' 
    } 
}); 

// load application 
System.import('script.js'); 

導入庫加載本地文件

// inside script.js 
import React from "react"; 
import ReactDOM from "react-dom"; 
import Header from "./header.js"; //note extension 

class Layout extends React.Component { 
+0

謝謝!很好地工作:) – xoomer

相關問題