【发布时间】:2018-08-09 18:35:26
【问题描述】:
我正在 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 也不太了解。谢谢!
P.s.:不幸的是,我目前无法测试这是否会返回任何错误,但一般的“你不应该这样做,因为......”会这样做:)
【问题讨论】:
-
但是
infoContent是一个实际的常量,还是它依赖于一些变量(即marker)?如果是这样,您可以导出一个名为getInfoContent的函数,该函数接受该参数并返回一个字符串。 -
您好,谢谢您的回复!目前它是一个保存 HTML 内容的常量,我想知道是否可以保持与其他变量的关系(
marker就是其中之一)。我想我明白了你的意思,这是有道理的。您能否用正式的答案详细说明一下?谢谢
标签: javascript reactjs google-maps export create-react-app