创建自定义 GeoJSON 组件的好方法是什么

IT技术 javascript reactjs leaflet geojson react-leaflet
2021-05-26 08:12:34

我需要帮助从 React-Leaflet 创建 GeoJSON 自定义组件

使用 React 和 React-Leaflet 编写(两个都是最新版本)代码在 Map 组件中写入时有效,但我想将其导入/导出以拆分代码

import React from 'react';
import { withLeaflet, GeoJSON } from 'react-leaflet'
import L from 'leaflet'


class CustomGesJSON extends GeoJSON {

    getStyle(feature) {
        // some code
    }

    pointToLayer(feature, latlng) {
        // some code
    }

    onEachFeature(feature, layer) {
        // some code
    }

    createLeafletElement(opts) {
        const CustomGesJSON = L.geoJSON.extend({

            onAdd: (map) => {
                this.getStyle = this.getStyle.bind(this);
                this.pointToLayer = this.pointToLayer.bind(this);
                this.onEachFeature = this.onEachFeature.bind(this);

                return this ;
            }
        });
        return new CustomGesJSON({ data: this.props.data });
    }


} 

function testlog(txt) {
    // some code
}

export default withLeaflet(CustomGesJSON);

我收到一条错误消息“GeoJSON 不是构造函数”

函数和方法(这里不显示)有效,我只需要帮助进行适当的继承 其他解决方案欢迎

谢谢你的帮助

1个回答

“react-leaflet”导出的“GeoJSON”对象可能不是ES6类,而是Leaflet L.GeoJSON“类”。

您可以使用 Leaflet 自己的 ES6 之前的类继承方案,如Leaflet 类理论教程中所述

const MyCustomClass = GeoJSON.extend({
  options: {
    onEachFeature: myCustomDefaultFunction
    // etc.
  }
});
export default MyCustomClass;