React Uncaught Reference Error - 未定义对象/类

时间:2016-03-22 04:12:20

标签: reactjs

我还是全新的反应。我尝试使用以下内容在index.html文件中创建:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>React Tutorial</title>
    <!-- Not present in the tutorial. Just for basic styling. -->
    <link rel="stylesheet" href="css/base.css" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.7/react.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.7/react-dom.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.6.15/browser.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/marked/0.3.5/marked.min.js"></script>
  </head>
  <body id="html-body">
    <div id="content"></div>
    <script type="text/babel" src="scripts/box.js"></script>
    <script type="text/babel">
    ReactDOM.render(
      <Box />,
      document.getElementById('content')
    );
    </script>
  </body>
</html>

scripts/box.js中,我有以下代码:

var Box = React.createClass({
  render: function() {
    return (
        <h2>Purple Monkey</h2>
    );
  }
});

当我在浏览器中查看index.html时,收到错误Uncaught ReferenceError: Box is not defined。但是当我在定义Box类之后将index.html中的ReactDOM.render行移动到scripts/box.js后,一切正常。

为什么我不能在ReactDOM.render之外执行scripts/box.js?如何正确包含/要求反应组件,以便其他javascript文件可以使用?

1 个答案:

答案 0 :(得分:1)

我将var Box =替换为window.Box =,然后一切正常。