react-leaflet创建自定义组件

时间:2018-08-24 22:51:35

标签: javascript reactjs leaflet react-leaflet

我想用react-leaflet创建一个自定义组件,该组件显示鼠标的实际位置(x,y),但是我不知道如何创建它。我找到了react-leaflet-control,但看来它不是最新的,当然我读了api文档https://react-leaflet.js.org/docs/en/custom-components.html,但我听不懂:/

有人可以给我一个自定义组件的例子吗,只需显示一个显示“ Hello world” 的组件即可。

2 个答案:

答案 0 :(得分:4)

根据documentation,要创建自定义组件,需要执行以下步骤:

1)扩展React-Leaflet提供的抽象类之一,例如:

class MapInfo extends MapControl {
   //...
} 

2)实现createLeafletElement (props: Object): Object方法来创建相关的Leaflet元素实例,例如:

createLeafletElement(opts) {
    const MapInfo = L.Control.extend({
      onAdd: (map) => {
        this.panelDiv = L.DomUtil.create('div', 'info');
        return this.panelDiv;
      }
    });
    return new MapInfo({ position: 'bottomleft' });
}

3)使用withLeaflet() HOC包装您的自定义组件,例如:

export default withLeaflet(MapInfo);

以下示例演示了如何创建自定义组件以显示鼠标在地图上的实际位置(lat,lng)

Demo

答案 1 :(得分:0)

@Vadim Gremyachev asnwer对我非常有用,但是我不得不花更多的时间在调试器和react-leaflet的库上。最后,我成功地从react-leaflet的import os path = 'C:\\Users\\brentond\\Desktop\\Lower Thames Crossing' for foldername, subfolders, filenames in os.walk(path): for subfolder in subfolders: for filename in filenames: if os.path.getsize(os.path.join(foldername, filename))>300000000: print(foldername + '\\' + filename) 抽象类扩展了CustomMarker组件。这最初是react-leaflet的MapLayer扩展的基础组件。问题在于,最初我已经实现了一个Marker方法,该方法使基本方法无法实现。因此,除此之外,我还必须在方法内部调用以下行。

componentDidMount

这告诉super.componentDidMount() MapLayer作为图层附加到传单地图上。

完整代码:

this.reactLeaflet

如果您的组件希望有一些子代,则也可以实现import React from 'react'; import { Marker as LeafletMarker } from 'leaflet'; import { MapLayer } from 'react-leaflet'; import { withLeaflet } from 'react-leaflet'; class CustomMarker extends MapLayer { //Whatever leaflet element this function return it will be assigned to this.leafletElement property. createLeafletElement(props) { let options = this.getOptions(props); const el = new LeafletMarker(props.position, options); let layer = props.leaflet.layerContainer; let map = props.leaflet.map; return el; } updateLeafletElement(fromProps, toProps) { if(fromProps.someProp != toProps.someProp){ //Modify this.leafletElement; } } componentDidMount() { super.componentDidMount(); let el = this.leafletElement } } export default withLeaflet(CustomMarker); 方法。检查它们如何在react-leaflet的原始组件中进行操作,例如上例中的render