具有自定义反应组件的 React-leaflet geojson onEachFeature 弹出窗口

ast*_*cus 8 popup geojson leaflet reactjs react-leaflet

我正在尝试在react-leaflet GeoJSON onEachFeature 弹出窗口中渲染自定义反应组件,例如用所有相应的feature.properties. 在弹出的反应传单组件中它效果很好

<Popup>
   Some text
   <Another React Component />
</Popup>
Run Code Online (Sandbox Code Playgroud)

但是 GeoJSON 的 onEachFeature 函数看起来像这样

onEachFeature(feature, layer) {
    const popupContent = `
        <div>
            <p>${feature.properties.name}</p>                  
        </div>
            `;
        layer.bindPopup(popupContent);
        }
Run Code Online (Sandbox Code Playgroud)

popupContent是一个html代码,我不知道如何在其中包含反应组件。需要帮忙!谢谢你!

kbo*_*oul 10

您可以使用ReactDOMServer.renderToString,请参阅此处,能够拥有自定义 Popup 组件,并通过layer.bindPopup将功能作为 prop 或您想要的任何其他 prop 传递来渲染它。

创建一个 Popup 组件,例如:

const Popup = ({ feature }) => {
  let popupContent;
  if (feature.properties && feature.properties.popupContent) {
    popupContent = feature.properties.popupContent;
  }

  return (
    <div>
      <p>{`I started out as a GeoJSON  ${
        feature.geometry.type
      }, but now I'm a Leaflet vector!`}</p>
      {popupContent}
    </div>
  );
};
Run Code Online (Sandbox Code Playgroud)

然后在里面使用onEachFeatureReactDOMServer.renderToString

const onEachFeature = (feature, layer) => {
    const popupContent = ReactDOMServer.renderToString(
      <Popup feature={feature} />
    );
    layer.bindPopup(popupContent);
  };
Run Code Online (Sandbox Code Playgroud)

编辑 提供更多信息后,我将代码更改为如下所示:

  1. 只是为了示例而创建一个模态,并将其状态、切换函数和选定的功能作为 props 传递。

  2. 迭代geojson并创建一个FeatureGroupreact-leaflet组件,而不是通过作为子react-leaflet组件传递来使用GeoJSON和监听事件。在里面你可以有你的按钮与所需的 onClick 事件。通过这种方式可以克服静态 html 的问题。创建一个标记,然后单击按钮并启用模式。单击该按钮后,您将保存所选的特征参考。onEachFeaturePopup

  3. 如果您想扩展示例以涵盖所有可能的几何类型,您可以检查几何属性并基于渲染圆或其他元素。

我还更新了演示。我希望现在可以为您提供更多帮助。

演示