问题描述
我为我的项目设置了React on Rails。我有一个可以渲染React组件的haml模板:
-# my_template.haml
%div
= react_component('MyComponent')
现在,如果我在另一个模板中渲染此模板,则它可以按预期工作,并且可以看到渲染的React组件。
-# my_other_template.haml
%div
= render 'my_template'
但是,如果我引用了某个组件或在capture_haml
块内渲染该组件的模板,则它不会渲染:
-# my_other_template.haml
- captured = capture_haml do
-# This does not work
= react_component('EliteSellerBadge')
-# This does not work
= render 'my_template'
%div
-# This works
= react_component('EliteSellerBadge')
-# This works
= render 'my_template'
-# This does not work
= captured
在可行的情况下,react组件将在div
内部呈现具有唯一{MyComponent-react-component-0b88d3fe-e457-4bec-b2a1-119097662161
的唯一ID,并在其旁边带有script
标签,其ID为{ {1}}。在不起作用的情况下(在js-react-on-rails-context
块内),将呈现具有唯一ID的div,但该div为空,并且在DOM中不会出现capture_haml
脚本标签。
是否无法在这样的js-react-on-rails-context
块内使用React on Rails组件,还是我做错了什么?
解决方法
我知道这已经有一段时间了,但我也遇到了一个问题,内容在问题中描述的 DOM 上,但 react 组件没有在浏览器上呈现。我认为在这种情况下,您需要通过执行预渲染反应组件;
= react_component('EliteSellerBadge',prerender: true)
就我而言,具有我需要呈现的组件的视图是通过 xhr 请求和 jquery replaceWith
方法添加的。
希望这对某人有所帮助。
PS:如果您在 React 组件中引用 window
和 document
等全局对象,则可能会遇到预渲染问题。