我正在尝试在react-leaflet GeoJSON onEachFeature弹出窗口中呈现自定义的react组件。以所有相应的feature.properties
触发模式。在弹出的react-leaflet组件中,它很好用
<Popup>
Some text
<Another React Component />
</Popup>
但是GeoJSON的onEachFeature函数看起来像这样
onEachFeature(feature, layer) {
const popupContent = `
<div>
<p>${feature.properties.name}</p>
</div>
`;
layer.bindPopup(popupContent);
}
popupContent
是html
代码,我不知道如何在其中包含react组件。需要帮忙!谢谢!
您可以使用ReactDOMServer.renderToString
,请参见here以拥有自定义的Popup组件,并通过将功能作为道具或您想要的任何其他道具传递,并使用layer.bindPopup
进行渲染。
例如创建一个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>
);
};
然后在onEachFeature
中与ReactDOMServer.renderToString
一起使用
const onEachFeature = (feature, layer) => {
const popupContent = ReactDOMServer.renderToString(
<Popup feature={feature} />
);
layer.bindPopup(popupContent);
};
编辑提供更多信息后,我将代码更改如下:
仅出于示例目的而创建模态,并将其状态,切换函数和selectedfeature作为道具传递。
在geojson上迭代并创建一个FeatureGroup
react-leaflet组件,而不是使用GeoJSON
并通过作为子级react-leaflet的Popup来监听onEachFeature事件。在其中,您可以使按钮具有所需的onClick事件。通过这种方式,可以解决静态html的问题。创建一个标记,然后单击按钮并启用模态。单击按钮后,将保存选定的功能参考。
如果要扩展示例以涵盖所有可能的几何类型,则可以检查几何属性并基于该渲染圆或另一个元素。
我还更新了演示。希望现在可以为您提供更多帮助。