我正在使用react-leaflet,并想向地图添加图例。
目前,我可以通过将地图的引用传递给自定义组件并呈现 null,同时让函数创建 HTML 并将其添加到地图来实现此目的。使用 Jest 和 Enzyme 进行测试对裁判来说是一场噩梦。
有没有办法使用react-leaflet组件来实现这一点?
您可以通过扩展来实现react-leaflet
's MapControl
类并使用例如 Leaflet 官方页面教程提供的图例代码将 GeoJSON 与 Leaflet 结合使用 https://leafletjs.com/examples/geojson/.
class Legend extends MapControl {
componentDidMount() {
// place your code here
...
const legend = L.control({ position: "bottomright" });
...
const { map } = this.props.leaflet;
legend.addTo(map);
}
}
然后将其导入此处:
<Map style={{ height: "100vh" }} center={position} zoom={13}>
<TileLayer
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
/>
<Legend />
</Map>
Demo https://codesandbox.io/s/how-to-add-a-legend-to-the-map-using-react-leaflet-6yqs5
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)