我已经阅读了一些有关此的答案,但似乎没有什么用。
我在React-Redux-Google Maps项目中有一个模块,该模块导出如下函数:
export default function(google, map, store) {
// Main module functionality
}
此函数被导入到我的initMap
模块中,并用google
,map
和store
进行调用。因此,此功能能够与地图互动,例如创建Google地图标记,折线等。
在此功能内,我创建了一个帮助程序功能来清除地图。我可以通过引用渲染对象并调用其方法.setMap(null)
(根据Google Maps API文档)来做到这一点。但是,我想导出该辅助函数,以便可以将其导入到我的React组件中并将其绑定到onClick
处理程序。
我知道我无法从导出的函数中导出帮助器函数。我也不能直接调用辅助函数。我也不能将辅助函数移到主函数之外(即它们在同一作用域内),因为它随后将无法访问google
,map
和store
变量。
我认为唯一可行的解决方案是重组主函数(默认导出)以返回对象:
{
main: main,
helper: helper
}
其中main
和助手是子功能。这样,两个子功能都可以访问google
,map
和store
变量,它们将在范围内。
即:
export default function(google, map, store) {
function main() {
// Main module functionality
}
function helper() {
// Helper module functionality
}
return {
main: main,
helper: helper
};
}
这是可行/不好的做法吗?
答案 0 :(得分:0)
如果这两个功能不是紧密相关的,则将这些功能存储在不同的文件中并同时导入这两个文件更有意义。
如果它们之间的关系更紧密(在这里似乎是这种情况),则可以将它们存储为类的静态方法,然后导出该类。此选项有助于将相关功能组织到帮助程序类的方法中,并且可以轻松完成工作。
export default class {
static main() {
// Main module functionality
}
static helper() {
// Helper module functionality
}
}