ruby-on-rails - 如何将react-rails与webpacker结合使用?

标签 ruby-on-rails reactjs webpack react-rails webpacker

我使用 webpacker 创建了示例项目react-rails。但显示错误“ Uncaught ReferenceError :未定义人员”。帮助我 如何将react-rails与webpacker一起使用? 我进行的处理如下。

Rails 版本

$ rails -v
Rails 5.0.2

gem 版

react-rails (2.1.0)
webpacker (1.1)

创建 Rails 项目

$ rails new example

将 webpacker 和 React-rails 添加到 Gemfile

gem 'webpacker', github: 'rails/webpacker'
gem "react-rails"

安装 webpacker 并使用react

$ rails webpacker:install
$ rails webpacker:install:react
$ rails generate react:install

创建 Controller

$ bin/rails g controller home

添加路线

config/routes.rb
root "home#index"

添加 react 组件

$ bin/rails g react:component person name --es6

添加react_component标签

app/views/home/index.html.erb
<%= react_component("Person", { name: "Hello" }) %>

将 javascript_pack_tag 添加到 application.html.erb

app/views/layouts/application.html.erb
<%= javascript_pack_tag 'application' %>

运行服务器

$ bin/rails s
$ bin/webpack-dev-server

显示错误控制台

VM27375:1 Uncaught ReferenceError: Person is not defined
    at eval (eval at module.exports (fromGlobal.js?fc31:13), <anonymous>:1:1)
    at module.exports (fromGlobal.js?fc31:13)
    at Object.getConstructor (fromRequireContextWithGlobalFallback.js?cbbb:16)
    at Object.mountComponents (index.js?c0e8:82)
    at HTMLDocument.ReactRailsUJS.handleMount (index.js?c0e8:124)
    at HTMLDocument.dispatch (jquery.self-bd7ddd3….js?body=1:5227)
    at HTMLDocument.elemData.handle (jquery.self-bd7ddd3….js?body=1:4879)

示例项目

https://github.com/yokochi/webpacker_example

最佳答案

app/javascript/components/person.js 重命名为 app/javascript/components/Person.js(例如大写)

或者使用react_component('person')代替。

TLDR;大小写很重要。

关于ruby-on-rails - 如何将react-rails与webpacker结合使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43558186/

相关文章:

javascript - 如何向具有多个加载器的 webpack 加载器添加查询?

ruby-on-rails - SSL 与 Ruby on Rails

ruby-on-rails - Rspec测试CSV文件下载

javascript - 为 Object.values() react Babel polyfill

javascript - 使用 ReactJS 的跨浏览器 flexbox 内联样式

javascript - CSS 过渡没有传递随机数

javascript - 导入有效,但为什么 require 不起作用?

angular - Uncaught Error : The template specified for component AppComponent is not a string

ruby-on-rails - 调用方法,在Application controller中定义,在其他controller中

ruby-on-rails - Rails 3 和 validate_on_create