我有一个简单的 React 组件,当前在客户端上正确呈现。我正在尝试将其呈现在服务器上。为了测试这一点,我关闭了 Chrome 中的 JavaScript 并加载页面。
我的组件如下所示:
window.TestComponent = React.createClass({
render: function() {
return React.DOM.h1({className: 'TestComponent'},
'Test Component')
}
});
入口点如下所示:
<%= react_component 'TestComponent', {prerender: true} %>
目前,页面加载没有错误,并包含以下内容:
<div data-react-class="TestComponent" data-react-props="{'prerender': true}"></div>
Rails 似乎正在解析 erb,但无法渲染它引用的组件。
我已将 Ruby Racer 包含在我的 Gemfile 中,并通过将一些计算打印到 DOM 来验证它是否正常工作。
根据 React Rails 文档中有关服务器端渲染的内容,有以下三个要求:
要求 1
react-rails must load your code. By convention, it uses components.js, which was created by the install task. This file must include your components and their dependencies (eg, Underscore.js).
我的组件位于:app/assets/javascripts/components/test_component.js.erb,应该由components.js中的JavaScript加载:
//= require_tree ./components
要求 2
Your components must be accessible in the global scope. If you are using .js.jsx.coffee files then the wrapper function needs to be taken into account:
我正在使用纯 JavaScript
要求3
Your code can't reference document. Prerender processes don't have access to document, so jQuery and some other libs won't work in this environment :(
我没有引用文档。
我可能做错了什么?
最佳答案
试试这个:
<%= react_component 'TestComponent', {}, {prerender: true} %>
第一个哈希是空的 - 它是 react 组件的空参数。
第二个哈希是react-rails的选项,这就是你说“prerender: true”的地方。
关于javascript - 使用 React Rails 预渲染 React 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37702279/