如何使用react-leaflet v3创建类组件?

Ton*_*BCN 3 react-leaflet

React-leaflet 包允许使用 leaflet 并使用功能组件进行反应,至少https://react-leaflet.js.org/上的所有示例都使用功能组件。是否可以在 React-leaflet 版本 3 中使用类组件?如果是的话,有例子吗?

Vad*_*hev 5

支持创建类组件,尽管react-leaflet v3与以前版本中官方支持的方式不同。

在版本中v1v2您应该通过以下方式实现自定义组件:

a) 扩展 提供的抽象类之一react-leaflet,例如:

class MapInfo extends MapControl {
   //...
} 
Run Code Online (Sandbox Code Playgroud)

b) 及实施createLeafletElement (props: Object): Object方法

请参阅此答案以获取更多详细信息,因为用于实现 v1 和 v2 版本的自定义组件的官方文档不再可用。


以下示例演示了如何将 自定义组件转换为 version 3

这是一个兼容 v1/v2 版本的自定义组件:

import React, { Component } from "react";
import { withLeaflet, MapControl } from "react-leaflet";
import L from "leaflet";

class MapInfo extends MapControl {
  constructor(props, context) {
    super(props);
    props.leaflet.map.addEventListener("mousemove", ev => {
      this.panelDiv.innerHTML = `<h2><span>Lat: ${ev.latlng.lat.toFixed(
        4
      )}</span>&nbsp;<span>Lng: ${ev.latlng.lng.toFixed(4)}</span></h2>`;
      console.log(this.panelDiv.innerHTML);
    });
  }

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

  componentDidMount() {
    const { map } = this.props.leaflet;
    this.leafletElement.addTo(map);
  }
}

export default withLeaflet(MapInfo);
Run Code Online (Sandbox Code Playgroud)

可以转换为以下与版本兼容的类组件3

class MapInfo extends React.Component {
 
  createControl() {
    const MapInfo = L.Control.extend({
      onAdd: (map) => {
        const panelDiv = L.DomUtil.create("div", "info");

        map.addEventListener("mousemove", (ev) => {
          panelDiv.innerHTML = `<h2><span>Lat: ${ev.latlng.lat.toFixed(4)}</span>&nbsp;<span>Lng: ${ev.latlng.lng.toFixed(4)}</span></h2>`;
          console.log(panelDiv.innerHTML);
        });
        return panelDiv;
      },
    });
    return new MapInfo({ position: "bottomleft" });
  }

  componentDidMount() {
    const {map} = this.props;
    const control = this.createControl();
    control.addTo(map);
  }

  render() {
    return null;
  }
}

function withMap(Component) {
  return function WrappedComponent(props) {
    const map = useMap();
    return <Component {...props} map={map} />;
  };
}

export default withMap(MapInfo);
Run Code Online (Sandbox Code Playgroud)

注意: withMap是一个高阶组件,旨在将地图实例传递到类组件中

这是一个演示