使用 requirejs 加载具有 parent/child 关系的 React 组件
Using requirejs to load React Components with a parent/child relationship
我正在使用 React/Flux 开发高度可插拔的 UI,并使用 RequireJS 加载模块。
我无法解决这个问题,可能是因为我对 RequireJS 的了解不多。还有一层间接,但是问题的根源是这样的:
我在具有以下渲染功能的模块中有 React 组件 A:
render: function() {
<div>
<Component B />
</div>
}
和组件 B,在一个单独的模块中会很简单,例如:
render: function() {
<div> Some Text </div>
}
在我使用 requirejs 深入研究的顶级模块中,我可以这样获取 componentA:
require(['ComponentA'], function(ComponentA) {
React.render(React.createElement(ComponentA,document.getElementById('main'));
});
这很好用,直到我尝试在 ComponentA 的渲染函数中使用 ComponentB...componentA 自然不知道 ComponentB 是什么,但我不确定正确的方法或如何在 componentA 之前要求 ComponentB尝试渲染。
注意:我事先将所有 JSX 转换为纯 JS,所以这不应该成为一个因素。
有什么建议吗?
听起来你的模块不是定义 - http://requirejs.org/docs/api.html#defdep
使用定义,ComponentA绝对可以得到ComponentB的引用,最简单的例子是这样的:
ComponentA - 具有依赖关系 - http://requirejs.org/docs/api.html#defdep
define(['path/to/ComponentB'], function (ComponentB) {
return React.createClass( {
render: function () {
<div>
<ComponentB />
</div>
}
});
});
ComponentB - 无依赖关系 - http://requirejs.org/docs/api.html#deffunc
define(function () {
return React.createClass( {
render: function () {
<div>
Some Text
</div>
}
});
});
然后您可以按照您在问题中提到的那样在顶层渲染 ComponentA,并且 ComponentA 将包含一个 ComponentB
我正在使用 React/Flux 开发高度可插拔的 UI,并使用 RequireJS 加载模块。
我无法解决这个问题,可能是因为我对 RequireJS 的了解不多。还有一层间接,但是问题的根源是这样的:
我在具有以下渲染功能的模块中有 React 组件 A:
render: function() {
<div>
<Component B />
</div>
}
和组件 B,在一个单独的模块中会很简单,例如:
render: function() {
<div> Some Text </div>
}
在我使用 requirejs 深入研究的顶级模块中,我可以这样获取 componentA:
require(['ComponentA'], function(ComponentA) {
React.render(React.createElement(ComponentA,document.getElementById('main'));
});
这很好用,直到我尝试在 ComponentA 的渲染函数中使用 ComponentB...componentA 自然不知道 ComponentB 是什么,但我不确定正确的方法或如何在 componentA 之前要求 ComponentB尝试渲染。
注意:我事先将所有 JSX 转换为纯 JS,所以这不应该成为一个因素。
有什么建议吗?
听起来你的模块不是定义 - http://requirejs.org/docs/api.html#defdep
使用定义,ComponentA绝对可以得到ComponentB的引用,最简单的例子是这样的:
ComponentA - 具有依赖关系 - http://requirejs.org/docs/api.html#defdep
define(['path/to/ComponentB'], function (ComponentB) {
return React.createClass( {
render: function () {
<div>
<ComponentB />
</div>
}
});
});
ComponentB - 无依赖关系 - http://requirejs.org/docs/api.html#deffunc
define(function () {
return React.createClass( {
render: function () {
<div>
Some Text
</div>
}
});
});
然后您可以按照您在问题中提到的那样在顶层渲染 ComponentA,并且 ComponentA 将包含一个 ComponentB