使用react-rails gem

时间:2019-03-06 07:35:47

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

我遵循react-rails中的“ webpacker入门”,但是在运行Rails服务器时,我看不到那里的hello world组件。

app / javascript / components / HelloWorld.js

import React from "react"
import PropTypes from "prop-types"
class HelloWorld extends React.Component {
  render () {
    return (
      <React.Fragment>
        Greeting: {this.props.greeting}
      </React.Fragment>
    );
  }
}

HelloWorld.propTypes = {
  greeting: PropTypes.string
};
export default HelloWorld

views / layout / application.html.erb

<!DOCTYPE html>
<html>
  <head>
    <title>MyApp</title>
    <%= csrf_meta_tags %>
    <%= csp_meta_tag %>

    <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
    <%= javascript_pack_tag 'application' %>
  </head>

  <body>
    <%= yield %>
  </body>
</html>

views / home / index.html.erb

<!DOCTYPE html>
    <html>
        <body>
            <p>Heloo</p>
            <%= react_component("HelloWorld", { greeting: "Hello from react-rails." }) %>
        </body>
    </html>

app / javascript / packs / application.js

/* eslint no-console:0 */
// This file is automatically compiled by Webpack, along with any other files
// present in this directory. You're encouraged to place your actual application logic in
// a relevant structure within app/javascript and only use these pack files to reference
// that code so it'll be compiled.
//
// To reference this file, add <%= javascript_pack_tag 'application' %> to the appropriate
// layout file, like app/views/layouts/application.html.erb


// Uncomment to copy all static images under ../images to the output folder and reference
// them with the image_pack_tag helper in views (e.g <%= image_pack_tag 'rails.png' %>)
// or the `imagePath` JavaScript helper below.
//
// const images = require.context('../images', true)
// const imagePath = (name) => images(name, true)

console.log('Hello World from Webpacker')
// Support component names relative to this directory:
var componentRequireContext = require.context("components", true)
var ReactRailsUJS = require("react_ujs")
ReactRailsUJS.useContext(componentRequireContext)

这是我尝试访问网页时得到的信息 react-rails webpage

编辑: 在视图中添加prerender:true(服务器端渲染),效果很好

<%= react_component("HelloWorld", { greeting: "Hello from react-rails." }, prerender: true) %>

但是为什么客户端渲染不起作用?

2 个答案:

答案 0 :(得分:0)

此问题与您的视图设置有关。

您的视图正在呈现完整的HTML文档,并且忽略了布局,因此JavaScript根本没有加载到页面上。这解释了为什么在窗口上所有内容都未定义。

在问题的屏幕截图中,您可以看到HTML HEAD为空。 用以下内容替换视图。

views / home / index.html.erb

<p>Heloo</p>
<%= react_component("HelloWorld", { greeting: "Hello from react-rails." }) %>

还可以通过暂时放置一些可见的内容来确保布局文件正确呈现。您可以暂时将视图内容放入模板中,以确保同时做到这两项!

希望这会有所帮助。

答案 1 :(得分:0)

尝试添加

 <%= javascript_pack_tag 'application' %>

在您的index.html.erb