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

How to use react-leaflet v3 to create class components?

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

支持在react-leaflet v3中创建class组件,虽然与之前版本官方支持的方式不同。

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

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

class MapInfo extends MapControl {
   //...
} 

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

获取更多详细信息,因为不再提供为 v1 和 v2 版本实现自定义组件的官方文档。


以下示例演示如何将自定义组件转换为版本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);

可以转换为以下 class 兼容版本 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);

Note: withMap is a high order component which is intended to pass map instance into class component

Here is a demo