Rails和React-React.createClass / React.createReactClass不是函数

时间:2018-10-31 10:46:12

标签: javascript ruby-on-rails ruby reactjs react-native

我正在尝试在Rails应用程序中使用React。我正在使用Rails 5.2.1和Ruby 2.4.1。我还安装了 react-rails gem版本2.4.4,并在2.4.7中进行了尝试。我有一个

sites_controller.rb

class SitesController < ApplicationController

  def index
  end
end

views / sites / index.html.erb

<%= react_component 'Main' %>

app / assets / javascripts / components / _main.js.jsx

var Main = React.createReactClass({
render() {
 return (
      <div>
        <Header />
      </div>    
   )
  }
})

app / assets / javascripts / components / _header.js.jsx

var Header = React.createReactClass({
 render() {
  return (
    <div>
      <h1>Hello, World!</h1>
    </div>
  );
}

});

我首先尝试了createClass,但由于它无法正常工作,并且一些链接说createClass已从React JS v16中删除,因此我尝试了createReactClass。我收到以下错误

  Uncaught TypeError: React.createReactClass is not a function
at _header.self- 
(anonymous) @ _header.self- 
 f50926322cbfc16ac78826d5bfa8a3f192af29cac5125c3955f9bef3355b54d9.js? 
  body=1:1
_main.self-1ed2e3a6d11c77d50ab4dd84f59f619d3ae85141ee36949c34885bb6b90992c4.js?body=1:1 Uncaught TypeError: React.createClass is not a function
at _main.self-1ed2e3a6d11c77d50ab4dd84f59f619d3ae85141ee36949c34885bb6b90992c4.js?body=1:1
(anonymous) @ _main.self-1ed2e3a6d11c77d50ab4dd84f59f619d3ae85141ee36949c34885bb6b90992c4.js?body=1:1
  react_ujs.self-eb4e9994228856e343ab49d1aed6c23046bf4308ea6d46395e5c39170ab3e56f.js?body=1:313 Uncaught Error: Cannot find component: 'Main'. Make sure your component is available to render.
    at Object.mountComponents (react_ujs.self-eb4e9994228856e343ab49d1aed6c23046bf4308ea6d46395e5c39170ab3e56f.js?body=1:313)
    at HTMLDocument.ReactRailsUJS.handleMount (react_ujs.self-eb4e9994228856e343ab49d1aed6c23046bf4308ea6d46395e5c39170ab3e56f.js?body=1:350)
    at Object.e.dispatch (turbolinks.self-569ee74eaa15c1e2019317ff770b8769b1ec033a0f572a485f64c82ddc8f989e.js?body=1:6)
    at r.notifyApplicationAfterPageLoad (turbolinks.self-569ee74eaa15c1e2019317ff770b8769b1ec033a0f572a485f64c82ddc8f989e.js?body=1:7)
    at r.pageLoaded (turbolinks.self-569ee74eaa15c1e2019317ff770b8769b1ec033a0f572a485f64c82ddc8f989e.js?body=1:7)
    at turbolinks.self-569ee74eaa15c1e2019317ff770b8769b1ec033a0f572a485f64c82ddc8f989e.js?body=1:6

2 个答案:

答案 0 :(得分:1)

这似乎是版本问题。我必须使用以下语法来使其正常工作。

class Main extends React.Component{
  render() {
    return (
      <div>
        <Header />
      </div>    
    )
  }
}

答案 1 :(得分:0)

相关文档在这里:

https://reactjs.org/docs/react-without-es6.html

通常,您将React组件定义为普通的JavaScript类:

class Greeting extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}

如果您还不使用ES6,则可以改用create-react-class模块:

var createReactClass = require('create-react-class');
var Greeting = createReactClass({
  render: function() {
    return <h1>Hello, {this.props.name}</h1>;
  }
});

ES6类的API与createReactClass()类似,但有一些例外。