gpt4 book ai didi

ruby-on-rails - 使用 react-rails gem 时 React 组件不呈现

转载 作者:行者123 更新时间:2023-12-04 15:47:42 26 4
gpt4 key购买 nike

我遵循了 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

编辑:在view中加入prerender: true(服务端渲染),完美运行

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

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

最佳答案

尝试添加

 <%= javascript_pack_tag 'application' %>

在你的 index.html.erb 中

关于ruby-on-rails - 使用 react-rails gem 时 React 组件不呈现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55017836/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com