leaflet - 使用 geojson pointToLayer 函数时需要正确的方法在 Leaflet 弹出窗口中呈现 jsx 组件
问题描述
嗨,有什么方法可以将 jsx 组件传递给 bindPopup 函数,这样我就可以在单击按钮时推送 redux 命令?
pointToLayer={(
geoJsonPoint: Feature<Point, DeviceProperties>,
latlng,
) => {
const marker = L.marker(latlng);
marker.setIcon(
markerIcon({ variant: geoJsonPoint.properties.relation }),
);
const sddds = (
<div className="font-quicksand">
<h2>{geoJsonPoint.properties.id}</h2>
<h2>{geoJsonPoint.properties.name}</h2>
<p>{geoJsonPoint.properties.description}</p>
<p>{geoJsonPoint.properties.ownerId}</p>
<a
onClick={() => {
dispatch(setDevice(geoJsonPoint.properties));
}}
>
Open device details
</a>
</div>
);
marker.bindPopup(renderToString(sddds));
return marker;
}}
我知道我可以使用反应传单组件,但这样我不能将道具传递给每个标记选项(我的意思是标记作为图层)。
解决方案
所以这已经讨论了一点。在讨论这个问题的 react-leaflet repo 中有一个问题,其结论是在bindPopup
方法中简单地使用 vanilla JS 来创建您的弹出窗口。我根本不喜欢这个解决方案,尤其是当您尝试从弹出窗口中使用非常面向反应的事件处理程序(如 react-redux 操作)时。
问题React-leaflet geojson onEachFeature popup with custom react component被问到,您可能已经阅读过,因为您renderToString
在代码中使用了 react 的方法。但是您可能已经发现,这不会维护您的 JSX 可能包含的任何交互性或 JS。那里的回答者提出了使用模式而不是弹出窗口的想法,但这并不能完全回答您的问题或在基于点层 geojson 的弹出窗口中真正使用 JSX。
最终,您将无法从pointToLayer
交互式函数返回 JSX。我认为这将是 react-leaflet 目前没有实现的一个很好的功能。在pointToLayer
函数的闭包中,没有直接编写功能齐全的 JSX 的好方法。
我玩了一会儿,试图利用pointToLayer
并保存feature
每次迭代的状态,然后从中渲染一个Marker
,Popup
但这让我思考 - 为什么要打扰?只需完全放弃组件并直接从 JSON 对象GeoJSON
呈现您Marker
的 s 和s 。Popup
像这样:
{myGeoJson.features.map((feature, index) => {
return (
<Marker
key={index}
position={L.latLng(feature.geometry.coordinates.reverse())}
>
<Popup>
<button
onClick={() => { yourReduxAction() }}
>
Click meeee
</button>
</Popup>
</Marker>
);
})}
工作沙箱
这样,您需要通过手动将 GeoJSON 转换为Marker
s with来更加努力地工作Popups
,但并不像尝试从 JSX ( <GeoJSON />
) 到 vanilla JS ( pointToLayer
) 再回到 JSX ( <Popup />
) 那样向后弯腰。
推荐阅读
- javascript - JWT 解码返回“[object Object]”
- javascript - 如何使用按钮重置反应表单输入值(与状态相关)?
- webpack - 使用 vuetify 加载器插件无法加载 CSS 样式和字体机器人(mdi 图标是)
- python - 如何从 Python 启动 Linux 提升权限窗口?
- python-3.x - python datetime strptime 意外输出
- r - 滚动平方根等函数
- jquery - ajax 在成功参数中是否有“值” - jquery?
- javascript - JavaScript onkeydown / addeventlistener
- javascript - 使用 angularfire2 分片到多个数据库
- angular - 无法绑定到“行”,因为它不是“ngx-datatable”的已知属性