我正在try 使用this教程让ReactJS与rails一起工作.我得到了这个错误:


Uncaught ReferenceError: React is not defined

But I can access the React object in browser consoleenter image description here
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

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

[EDIT 1]

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);

这是我的index.html.erb:

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

推荐答案

当我使用webpack构建javascript时,我能够重现这个错误,在我的webpack.config.json个页面中有以下区块:

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

上述配置告诉webpack不要通过加载npm模块来解析require('react'),而是期望一个名为React的全局变量(即window对象上的变量).解决方案是要么删除这段配置(因此React将与javascriptBundle 在一起),要么在执行该文件之前从外部加载React框架(因此window.React存在).

Ruby-on-rails相关问答推荐

通过激励控制器正确更新Turbo帧信源

在Ruby on rails中,重复访问ActiveRecordModel返回相同的对象:预期行为还是错误?

ActiveAdmin:的呈现索引表在父级的显示页中有许多资源

具有 IN 子句的参数化查询在 ruby​​-on-rails 的 blazer 工具中无法按预期工作

Rails HMAC - 使用应用程序机密作为加密密钥

如何断言 Ruby 单元测试中的错误消息?

rails 3:将链接显示为按钮?

在 Rails 中将毫秒转换为格式化日期

如何判断是否已经在 ruby​​ on rails 的数据库事务中?

在一行中更改多个对象属性

Rails Mailer Net::OpenTimeout: execution expired 仅在生产服务器上出现异常

可能在rails中有多态has_one关系?

.increment vs += 1

警告:引用了顶级常量

使用 AJAX 向 Rails 发送 Authenticity Token 的正确方法

快速添加链接[:notice]

ActiveRecord 事务中的错误处理?

您将如何解析 Ruby 中的 url 以获取主域?

为什么不对 Rspec + Selenium 使用共享的 ActiveRecord 连接?

扩展 Devise SessionsController 以使用 JSON 进行身份验证