繁体   English   中英

如何使用react传单在不使用ref和手动修改DOM的情况下向地图添加图例?

[英]How to add a legend to the map using react leaflet, without using refs and manually modifying the DOM?

我正在使用react-leaflet,并想在地图上添加图例。

我目前可以通过将地图的ref传递到自定义组件并在使函数创建HTML并将其添加到地图的同时呈现null的方式来完成此操作。 裁判正在使用Jest和Enzyme进行测试,这是一场噩梦。

有没有办法使用react-leaflet组件来完成此任务?

您可以通过扩展react-leafletMapControl类并使用(例如)Leaflet官方页面教程提供的图例代码( 将GeoJSON与Leaflet结合使用)来实现

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='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
        />
        <Legend />
 </Map>

演示版

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM