首页 > 解决方案 > 可以导入变量并在函数内部使用它们吗?

问题描述

我正在 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:不幸的是,我目前无法测试这是否会返回任何错误,但一般来说“你不应该这样做,因为......”会这样做:)

标签: javascriptreactjsgoogle-mapsexportcreate-react-app

解决方案


绝对鼓励将 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);

推荐阅读