【问题标题】:react-leaflet create a custom componentsreact-leaflet 创建自定义组件
【发布时间】:2018-08-24 22:51:35
【问题描述】:

我想用 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


    【解决方案1】:

    根据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

    【讨论】:

    • 非常感谢! ?
    • 您好,Demo 无法使用 react-leaflet v3.0.3
    【解决方案2】:

    @Vadim Gremyachev asnwer 对我非常有用,但我不得不在调试器和 react-leaflet 的库上多花几个小时。最后,我成功地从 react-leaflet 的 MapLayer 抽象类扩展了一个 CustomMarker 组件。这最初是 react-leaflet 的 Marker 扩展的基础组件。问题是,最初我实现了一个 componentDidMount 方法,它隐藏了基础方法。因此,除此之外,我还必须在我的方法中调用以下行。

    super.componentDidMount()
    

    这告诉MapLayerthis.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 中。

    【讨论】:

    • 能否请你给我一个完整的例子......也许在 jsfiddle 上?我尝试了同样的方法......但仍然有一些困难,因为我在 react-leaflet 中很新。谢谢。
    • 告诉我你到底想做什么,我会尽力帮助你?
    猜你喜欢
    • 1970-01-01
    • 2020-11-06
    • 2014-11-03
    • 2016-01-26
    • 2020-07-02
    • 2020-04-25
    • 1970-01-01
    • 1970-01-01
    • 2012-06-21
    相关资源
    最近更新 更多