Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 反应未捕获引用错误-未定义对象/类_Reactjs - Fatal编程技术网

Reactjs 反应未捕获引用错误-未定义对象/类

Reactjs 反应未捕获引用错误-未定义对象/类,reactjs,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

我还完全没有反应过来。我尝试在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>
在浏览器中查看index.html时,会出现错误
uncaughtreferenceerror:Box未定义
。但是当我在定义box类之后将index.html中的
ReactDOM.render
行移动到
scripts/box.js
中时,一切都正常


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

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

@John我不知道
标记是如何在后台编译的,它们可能有自己的作用域。作为一个实验,做
window.Box=React.createClass
有效吗?@azium哦,这很有趣……如果我用
window.Box=
替换
var-Box=
,那么一切都有效。这是怎么回事?因为babel会将您的代码重写为包含模块的闭包,这大概就是您通常不使用babel客户端的原因,您将应用程序编译成一个包,然后客户端加载它。看起来脚本类型
text/babel
创建了自己的范围,与函数类似,
vars
仅在函数的闭包内可用。这种写React的方式不是为了生产,只是为了掌握事情的诀窍。现在,只要把东西放在同一个脚本标签上,一旦你觉得舒服,就拿出一个样板,从那里开始像这样编码
var Box = React.createClass({
  render: function() {
    return (
        <h2>Purple Monkey</h2>
    );
  }
});