我用webpacker创建了一个示例项目react-rails。但显示错误“未捕获ReferenceError:未定义人员”。请告诉我如何在webpacker中使用react-rails?我执行的处理如下所示。
Rails版本
$ rails -v
Rails 5.0.2Gem版本
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创建控制器
$ 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" }) %>向application.html.erb添加javascript_pack_tag
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)示例项目
发布于 2017-05-03 14:15:17
将app/javascript/components/person.js重命名为app/javascript/components/Person.js (例如大写)
或者改用react_component('person')。
TLDR;大写很重要。
发布于 2017-05-12 22:20:13
@Akio Yamazaki
你应该在你的组件和导出组件中要求(‘react’)
试试这个。
var React = require("react")
class Person extends React.Component {
render () {
return (
<div>
<div>Name: {this.props.name}</div>
</div>
);
}
}
Person.propTypes = {
name: React.PropTypes.node
};
module.exports = Person但是这种方式会更好
import React from 'react'
class Person extends React.Component {
constructor(props){
super(props)
}
render() {
<div>Name: {this.props.name}</div>
}
}
export default Person或者..。
import React from 'react'
const Person = props => (
<div>Name: {props.name}</div>
)
export default Person我有一个回购,也许可以提供一些参考。
https://github.com/kakas/react-rails_with_webpacker_example/commits/master
发布于 2019-12-28 05:33:42
也许太晚了,我遇到了同样的问题,我解决了在Gemfile中更改版本的问题;这应该是可行的:
gem 'react-rails', '~> 1.7', '>= 1.7.1'https://stackoverflow.com/questions/43558186
复制相似问题