未捕获的 ReferenceError:未定义 React

2022-01-31 00:00:00 reactjs ruby-on-rails javascript

我正在尝试使用
我还添加了 public/dist/turbo-react.min.js 描述 here 并在 application.js 中添加 //= require components 行,如 在这个答案中没有运气.此外,
var React = require('react') 给出错误:
Uncaught ReferenceError: require is not defined

谁能建议我如何解决这个问题?


源代码供参考:
这是我的 comments.js.jsx 文件:

var Comment = React.createClass({渲染:函数(){返回 (<div className="comment"><h2 className="commentAuthor">{this.props.author}</h2>{this.props.comment}</div>);}});var 就绪 = 函数 () {React.renderComponent(<评论作者=理查德"评论=这是评论"/>,document.getElementById('comments'));};$(文档).ready(准备好);

这是我的index.html.erb:

<div id="comments"></div>

解决方案

当我使用 webpack 在我的 webpack.config.json:

外部:{反应":反应"},

上面的配置告诉 webpack 不要通过加载 npm 模块来解析 require('react'),而是期待一个全局变量(即在 window 对象上) 称为 React.解决方案是删除这部分配置(因此 React 将与您的 javascript 捆绑在一起)或在执行此文件之前从外部加载 React 框架(以便 window.React 存在).

I am trying to make ReactJS work with rails using this tutorial. I am getting this error:


Uncaught ReferenceError: React is not defined

But I can access the React object in browser console
I also added public/dist/turbo-react.min.js as described here and also added //= require components line in application.js as described in this answer to no luck. Additionally,
var React = require('react') gives the error:
Uncaught ReferenceError: require is not defined

Can anyone suggest me on how to resolve this?

[EDIT 1]
Source code for reference:
This is my comments.js.jsx file:

var Comment = React.createClass({
  render: function () {
    return (
      <div className="comment">
        <h2 className="commentAuthor">
          {this.props.author}
        </h2>
          {this.props.comment}
      </div>
      );
  }
});

var ready = function () {
  React.renderComponent(
    <Comment author="Richard" comment="This is a comment "/>,
    document.getElementById('comments')
  );
};

$(document).ready(ready);

And this is my index.html.erb:

<div id="comments"></div>

解决方案

I was able to reproduce this error when I was using webpack to build my javascript with the following chunk in my webpack.config.json:

externals: {
    'react': 'React'
},

This above configuration tells webpack to not resolve require('react') by loading an npm module, but instead to expect a global variable (i.e. on the window object) called React. The solution is to either remove this piece of configuration (so React will be bundled with your javascript) or load the React framework externally before this file is executed (so that window.React exists).

相关文章