我想在我的Rails 4.2.4应用程序中使用react-rails gem(版本2.1) . 我've gone through the setup steps in the Readme and I' m使用webpacker进行js预处理 . 我在 app/javascript/components/label.js
中有一个组件,如下所示:
import React, {PureComponent} from 'react';
import ReactDOM from 'react-dom'
export default class Label extends PureComponent {
render () {
return (
<div>Something rendered in React</div>
)
}
}
然后我在我的视图中使用以下行引用它:
= react_component("Label")
从自述文件中我可以看出,这应该是渲染组件所需的全部内容(如果应用程序包包含在布局中,它就是这样)
= javascript_pack_tag 'application'
所以我很困惑为什么我在浏览器中收到组件未定义的错误 .
Uncaught ReferenceError: Label is not defined
打开 app/javascript/packs/application.js
我可以看到以下内容:
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)
首先,我验证了控制台日志显示在浏览器中(它是) . 我不确定 componentRequireContext
是做什么的,但如果它是相对于当前文件,那么它似乎很奇怪它指向 components
而不是 ../components
,但更改它不会渲染组件 . 但是,如果我添加以下行,我可以获得组件呈现:
window.Label = require('../components/label.js');
我认为React Rails gem会照顾这个,只要组件保存在 app/javascript/components
目录中?自述文件中没有任何内容表明我需要明确声明并要求组件,或者我错了?
1 回答
看起来你有大写问题 . 你将文件命名为'label.js',但是你正在寻找'= react_component(“Label”)'所以它看起来并没有找到什么是Label . 然后当你在窗口上设置Label然后反应就像“哦,好吧,Label实际上是label.js” . 它做的东西 . TLDR资本化很重要 .