this.props.children 在尝试使用@react-google-maps 对数组中的标记进行聚类时不是函数

this.props.children is not a function when trying to cluster markers from array using @react-google-maps

我正在尝试获取具有 lat/long 个点的对象数组并为每个对象创建一个 Marker,然后将这些 Marker 传递到 <MarkerClusterer>零件。

通过直接复制文档 here 我可以让它工作。然而,他们的方法与我需要的有点不同。

区别似乎在于点映射到组件的方式。

工作代码:

<MarkerClusterer
      options={{imagePath:"https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m"}}
    >
      {
        (clusterer) => [
          {lat: -31.563910, lng: 147.154312},
          {lat: -33.718234, lng: 150.363181},
          {lat: -33.727111, lng: 150.371124},
          {lat: -33.848588, lng: 151.209834}
        ].map((location, i) => (
          <Marker
            key={i}
            position={location}
            clusterer={clusterer}
          />
        ))
      }
    </MarkerClusterer>

我的非工作代码:

const listings = [
    { lat: -31.56391, lng: 147.154312 },
    { lat: -33.718234, lng: 150.363181 },
    { lat: -33.727111, lng: 150.371124 },
    { lat: -33.848588, lng: 151.209834 },
  ];
  let testArray = [];
  for (let i = 0; i < listings.length; i++) {
    let location = listings[i];
    testArray.push(
      <Pin position={location} id={i} key={i} clusterer={listings} />
    );
  }
...

 <MarkerClusterer>
    {testArray}
 </MarkerClusterer>

这里有一个 codesandbox 示例。代码在 Map2.js 下,不同之处在第 61 行。

我不知道第一种方法在做什么,而我不是。也许集群参考?在这方面的任何帮助将不胜感激。

<MarkerClusterer> 组件需要一个函数作为其子属性。该函数将由 <MarkerClusterer> 组件的渲染函数调用。在第二种情况下,您将传递一个数组作为子道具。因此 MarkerClusterer 试图将您的数组作为函数调用 (testArray()),因此失败了。

这应该有效

<MarkerClusterer
  options={{
    imagePath:
      "https://developers.google.com..."
  }}
>
  {clusterer =>
    listings.map((location, i) => (
      <Pin key={i} position={location} clusterer={clusterer} />
    ))
  }
</MarkerClusterer>

这在反应世界中被称为渲染道具。阅读 here 了解更多详情。