反应组件未在我的视图上呈现

Vic*_*ira 5 ruby-on-rails reactjs

我在项目上安装了react-rails,并添加了

gem 'react-rails'
Run Code Online (Sandbox Code Playgroud)

然后我用

rails g react:install
Run Code Online (Sandbox Code Playgroud)

我有我的索引html index.html.erb,带有react_component帮助器,它调用我的componnet

<%= react_component("Post", {title: "Hello World"}) %>
Run Code Online (Sandbox Code Playgroud)

我在app / assets / javascript / components / post.jsx中有这个帖子组件

class Post extends React.Component {
  render() {
    return <h1>{this.props.title}</h1>    
  }
}
Run Code Online (Sandbox Code Playgroud)

但是我的组件没有在屏幕上渲染

为什么?

Vic*_*ira 9

只需要在组件中添加 prerender: true 就可以了。

<%= react_component("Post", {title: "Hello World"}, {prerender: true}) %>
Run Code Online (Sandbox Code Playgroud)

  • 注意:当添加“预渲染”时,您是说该组件将在服务器端渲染。如果您导入任何未在“server_rendering.js”中列出的依赖项,它将引发错误。 (2认同)

小智 8

确保您已将<%= javascript_pack_tag 'application' %>指令添加到布局文件中。

同样在我的情况下,我忘记rails generate react:install按照此处指定的方式运行:https : //github.com/reactjs/react-rails#3-now-run-the-installers,它在 app/javascript/packs/application 中设置 ReactRailsUJS 设置。 js


dpa*_*ari -3

我相信渲染函数中的返回部分需要括号:

class Post extends React.Component {
  render() {
    return (<h1>{this.props.title}</h1>)
   }
}
Run Code Online (Sandbox Code Playgroud)