6

我用 webpacker 创建了示例项目 react-rails。但显示错误“未捕获的 ReferenceError:未定义人员”。帮助我如何在 webpacker 中使用 react-rails?我执行的处理如下。

导轨版本

$ rails -v
Rails 5.0.2

宝石版

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 并做出反应

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

创建控制器

$ bin/rails g controller home

添加路线

config/routes.rb
root "home#index"

添加反应组件

$ 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

4

3 回答 3

2

@山崎昭夫

https://github.com/yokochi/webpacker_example/commit/55ca96c1257e611dfb17b27fe53b402a97d5dedc#diff-0c7c7cb70dec34ec9dcff19a0f5bd40bR1

您应该在组件和导出组件中使用 require('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

于 2017-05-12T14:20:12.657 回答
2

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

react_component('person')改为使用。

TLDR;资本化问题。

于 2017-05-03T06:15:17.157 回答
0

也许为时已晚,我遇到了同样的问题,我在 Gemfile 中解决了更改版本;这应该工作:

gem 'react-rails', '~> 1.7', '>= 1.7.1'
于 2019-12-27T21:33:41.657 回答