带有自定义反应组件的 React-leaflet geojson onEachFeature 弹出窗口
React-leaflet geojson onEachFeature popup with custom react component
我正在尝试在 react-leaflet GeoJSON onEachFeature 弹出窗口中呈现自定义反应组件,例如用所有对应的 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
代码,我不知道如何在其中包含反应组件。需要帮忙!谢谢!
您可以使用 ReactDOMServer.renderToString
,请参阅 here 以能够拥有自定义 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>
);
};
然后在 onEachFeature
中与 ReactDOMServer.renderToString
一起使用
const onEachFeature = (feature, layer) => {
const popupContent = ReactDOMServer.renderToString(
<Popup feature={feature} />
);
layer.bindPopup(popupContent);
};
编辑
在提供更多信息后,我将代码更改为:
仅为示例创建一个模态,并将其状态、切换函数和所选功能作为道具传递。
遍历 geojson 并创建一个 FeatureGroup
react-leaflet 组件,而不是使用 GeoJSON
并监听 onEachFeature
事件,传递为children react-leaflet 的 Popup
组件。在那里你可以让你的按钮带有所需的 onClick 事件。通过这种方式可以克服静态 html 的问题。创建一个标记,然后单击按钮并启用模式。单击该按钮后,您将保存选定的特征参考。
如果您想扩展示例以涵盖所有可能的几何类型,您可以检查几何 属性 并基于该渲染圆或其他元素。
我也更新了演示。
希望现在能帮到你更多。
我正在尝试在 react-leaflet GeoJSON onEachFeature 弹出窗口中呈现自定义反应组件,例如用所有对应的 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
代码,我不知道如何在其中包含反应组件。需要帮忙!谢谢!
您可以使用 ReactDOMServer.renderToString
,请参阅 here 以能够拥有自定义 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>
);
};
然后在 onEachFeature
中与 ReactDOMServer.renderToString
const onEachFeature = (feature, layer) => {
const popupContent = ReactDOMServer.renderToString(
<Popup feature={feature} />
);
layer.bindPopup(popupContent);
};
编辑 在提供更多信息后,我将代码更改为:
仅为示例创建一个模态,并将其状态、切换函数和所选功能作为道具传递。
遍历 geojson 并创建一个
FeatureGroup
react-leaflet 组件,而不是使用GeoJSON
并监听onEachFeature
事件,传递为children react-leaflet 的Popup
组件。在那里你可以让你的按钮带有所需的 onClick 事件。通过这种方式可以克服静态 html 的问题。创建一个标记,然后单击按钮并启用模式。单击该按钮后,您将保存选定的特征参考。如果您想扩展示例以涵盖所有可能的几何类型,您可以检查几何 属性 并基于该渲染圆或其他元素。
我也更新了演示。 希望现在能帮到你更多。