如何处理 React 嵌套组件循环依赖?(使用 es6 类)
How to handle React nested component circular dependency? (using es6 classes)
我正在使用 React 和 Babel (es6)。我在解决组件之间的循环依赖关系时遇到问题。
我正在构建一个菜单,我们有:
- 项目工厂
- 项目文件夹
- 项目通用
- 更多项目类型商品
ItemFactory
只是根据传递的 props 返回任何其他组件。
ItemFolder
需要能够重用ItemFactory
,以构建嵌套的菜单项。
ItemFactory 组件,itemFactory.js(简化):
// I need ItemFolder
import ItemFolder from './itemFolder'
// import all different items too
...
function ItemFactory (props) {
switch (props.type) {
case 'link': return <ItemLink {...props} />
case 'blank': return <ItemBlank {...props} />
case 'folder': return <ItemFolder {...props} />
default: return <ItemGeneric {...props} />
}
}
modules.exports = ItemFactory
项目文件夹组件,项目文件夹.js(简化):
// I need the itemFactory
import ItemFactory from './itemFactory'
...
Items = props.items.map(item => {
return <ItemFactory {...item} />
})
module.exports = ItemFolder
如您所见,两者都需要彼此。这会导致一些循环依赖问题,我得到一个空对象。
任何帮助表示赞赏:)
在依赖关系圈中,导入的项将被解析为尚未初始化的导出绑定。如果您不立即使用它们(例如调用函数),这应该不会引起任何问题。
您的问题可能是使用 CommonJs 导出语法。以下方法应该有效:
// itemFactory.js
import ItemFolder from './itemFolder'
…
export default function ItemFactory(props) {
switch (props.type) {
case 'link': return <ItemLink {...props} />
case 'blank': return <ItemBlank {...props} />
case 'folder': return <ItemFolder {...props} />
default: return <ItemGeneric {...props} />
}
}
// itemFolder.js
import ItemFactory from './itemFactory'
…
export default function ItemFolder(props) {
let items = props.items.map(item => {
return <ItemFactory {...item} />
})
…
}
一种方法是将各个组件注入ItemFactory
。 这样做的好处是使工厂更容易使用新类型进行扩展:
const components = {};
export function registerComponent(name, Component) {
components[name] = Component;
};
export default function ItemFactory(props) {
const C = components[props.type];
return <C {...props} />;
}
// ItemFolder.js
import {registerComponent}, ItemFactory from 'itemFactory';
export default class ItemFolder {
...
};
registerComponent("folder", ItemFolder);
相关文章:
- ES6构造函数返回基类的实例
- 如何在下面的ES6循环中获得前面的文本
- 在自定义mean.io包中使用angular-chart.js作为依赖项
- 为什么Airbnb风格指南说不鼓励依赖函数名称推断
- es6 相当于下划线查找位置
- 如何在Javascript/ES6中的Aurelia浏览器应用程序中使用AWS S3
- 将依赖外部库的UMD模块与browserfy捆绑在一起
- 如何将本地依赖项添加到npm项目中
- 如何在内联依赖项并将图像转换为dataURI的情况下完全提取网页
- jquery中的复选框依赖项
- 使用ES6类语法在控制器中分配依赖项
- ES6模块导入和依赖关系管理
- 当使用Angular1+ES6时,控制器函数中未定义依赖注入,控制器是一个类
- 角度1.5&ES6-依赖项注入
- 在单元测试时模拟 ES6 依赖项
- 如何处理 React 嵌套组件循环依赖?(使用 es6 类)
- 如何使用 ES6 在 AngularJs 中进行依赖注入
- 什么's angular的优点;当我可以在es6中使用导入/导出时,s依赖项注入
- 如何在不使用ES6类特性的情况下在Aurelia中注入依赖
- ES5和ES6中的Angular 2依赖注入