可以导入变量并在函数内部使用它们吗?
Is it ok to import variables and use them inside of a function?
我正在 React 中试验 Google 地图 API,并且我有这个功能可以创建信息窗口以在检查 API 数据是否为标记后绑定到标记正确检索:
createInfoWindow( marker, infoWindow ) {
fetchData ? infoWindow.setContent( infoWindowContent ) :
infoWindow.setContent( infoWindowError );
infoWindow.open( map, marker );
}
现在,不再像这样在 .setContent() 方法中定义信息窗口内容:
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 的了解也不多。谢谢!
P.s.: 不幸的是,我目前无法测试 returns 是否有任何错误,但一般 "you shouldn't do this anyway, because..." 会做:)
绝对鼓励分离 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);
我正在 React 中试验 Google 地图 API,并且我有这个功能可以创建信息窗口以在检查 API 数据是否为标记后绑定到标记正确检索:
createInfoWindow( marker, infoWindow ) {
fetchData ? infoWindow.setContent( infoWindowContent ) :
infoWindow.setContent( infoWindowError );
infoWindow.open( map, marker );
}
现在,不再像这样在 .setContent() 方法中定义信息窗口内容:
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 的了解也不多。谢谢!
P.s.: 不幸的是,我目前无法测试 returns 是否有任何错误,但一般 "you shouldn't do this anyway, because..." 会做:)
绝对鼓励分离 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);