javascript - 可以导入变量并在函数内部使用它们吗?
问题描述
我正在 React 中尝试使用 Google Maps API,并且我有这个函数可以在检查 API 数据是否被正确检索后创建信息窗口以绑定到标记:
createInfoWindow( marker, infoWindow ) {
fetchData ? infoWindow.setContent( infoWindowContent ) :
infoWindow.setContent( infoWindowError );
infoWindow.open( map, marker );
}
现在,不要在 .setContent() 方法中直接定义 infowindows 内容,如下所示:
infoWindow.setContent(
'</div>' +
'<h2>Title: ' + marker.title'</h2>' +
'<p>Coords: ' + marker.position'</p>' +
'</div>'
) ...
我宁愿在另一个文件中定义内容,然后在方法中导出常量,如下所示:
文件:InfoWindow.js
export const infoContent = `<div>...</div>`;
然后简单地说:
import { infoContent } from "./InfoWindow.js";
infowWindow.setContent( infoContent ) ...
澄清一下,我想知道这样做是否是一个好习惯,因为我对 React 非常陌生,而且对 ES6 也不太了解。谢谢!
Ps:不幸的是,我目前无法测试这是否会返回任何错误,但一般来说“你不应该这样做,因为......”会这样做:)
解决方案
绝对鼓励将 HTML 内容解耦以保持 IMO 的可读性。我建议允许您通过marker
的是使用 getter 实用程序函数,然后导出:
export function getInfoContent({ title, position }) {
return `…` // HTML content, you can use title and position from marker here
}
然后调用 getter 并传入marker
:
infoWindow.setContent(getInfoContent(marker))
我相信这比内联 HTML 模板文字更具可读性,并将它们解耦,使其对读者更具声明性。另请注意您的三元表达式:
fetchData ? infoWindow.setContent( infoWindowContent ) :
infoWindow.setContent( infoWindowError );
总体思路是不使用条件运算符来执行两个不同的调用,而是使用运算符来选择传递的表达式:
infoWindow.setContent(fetchData ? infoWindowContent : infoWindowError);
推荐阅读
- excel - 如何通过 Powershell 捕获 Excel 宏的错误消息?
- flutter - 相同的代码在不同的机器上生成不同的黄金图像
- swift - 如何检测 AVQueuePlayer 播放完毕?
- c++ - 有符号整数类型的大小可以不同于 C/C++ 中对应的无符号类型的大小吗?
- c# - 在 .net SDK MYOB 中进行调用时是否需要 ICompanyFileCredentials
- laravel - 在 mpdf 中生成 pdf 时,如何修复 Laravel 中的 Class doi 不存在错误?
- python - 我可以跨多个文件创建一个相互引用的 sqlalchemy 类吗
- javascript - 将多个json文件导入一个js数组
- r - 如何在 r 中按时间聚合/求和值
- c# - 领域驱动设计:订单和订单线类