react-leaflet 创建自定义组件

问题描述 投票:0回答:3

我想使用react-leaflet创建一个自定义组件来显示鼠标的实际位置(x,y),但我不知道如何创建它。我找到了

react-leaflet-control
但似乎不是最新的,当然我阅读了api文档https://react-leaflet.js.org/docs/en/custom-components.html但我没有明白了:/

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

javascript reactjs leaflet react-leaflet
3个回答
11
投票

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

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)

演示


1
投票

@Vadim Gremyachev asnwer 对我来说非常有用,但我不得不花更多的时间来使用我的调试器和react-leaflet 的库。最后,我成功地从react-leaflet的

CustomMarker
抽象类中扩展了一个
MapLayer
组件。这最初是react-leaflet 的
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);

如果您的组件希望有一些子组件,您还可以实现

render
方法。检查他们如何在react-leaflet的原始组件中做到这一点,就像上面示例中的
Marker
中一样。


0
投票

对于使用

react-leaflet@4
的人:似乎我们可以使用
createControlComponent()
,如此处记录的

const MapInfo = createControlComponent( (option) => { const MapInfo = L.Control.extend({ onAdd: (map) => { const panelDiv = L.DomUtil.create('div', 'info') return panelDiv }, }) return new MapInfo({ position: 'bottomleft' }) }, )
    
© www.soinside.com 2019 - 2024. All rights reserved.