使用 react-leaflet-editable 和 react-leaflet 2.8.0

using react-leaflet-editable with react-leaflet 2.8.0

我 integrating/including react-leaflet-editable 我现有的项目 100% 依赖 react-leaflet v2.8.0。我目前无法升级,因为它需要对整个项目进行太多更改。我们目前负担不起的东西。 (当一个人可以为所有人改变时,为什么要为一个人改变一切。是的,我们可能有一天会这样做,但不是现在)

下面是代码。它与 react-leaflet v.3.x 完美配合,但当我切换到“2.8.0 版”时,它就开始工作了。

我尝试过的; Map3.x 中重命名为 MapContainer 所以我更改了它,但问题变成了 whenCreated={setMap} 参数。我需要一种方法将 link 编辑到 ReactLeafletEditable。或者至少我认为这是问题所在。

希望我解释得很好。代码和 link 如下。

import React, { useRef } from "react";
import L, { Icon } from "leaflet";
import "leaflet-editable";
import ReactLeafletEditable from "react-leaflet-editable";
import {
  MapContainer,
  TileLayer,
  LayersControl,
  LayerGroup
} from "react-leaflet";
import "leaflet/dist/leaflet.css";

function Demo() {
  const editRef = useRef();
  const [map, setMap] = React.useState();

  const editPolygon = () => {
    editRef.current.startPolygon();
  };

  return (
    <ReactLeafletEditable ref={editRef} map={map}>
      <button onClick={editPolygon} className="editable-btn">
        Create Polygon
      </button>
      <MapContainer
        style={{
          height: "700px",
          backgroundColor: "",
          flexGrow: "1",
          cursor: `10`
        }}
        editable={true}
        zoom={4}
        maxZoom={18}
        center={[35, 105]}
        whenCreated={setMap}
      >
        <LayerGroup>
          <TileLayer
            attribution='&amp;copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
            url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
          />
          <TileLayer url="http://tiles.openseamap.org/seamark/{z}/{x}/{y}.png" />
        </LayerGroup>
      </MapContainer>
    </ReactLeafletEditable>
  );
}

export default Demo;

Link 到 3.0 中的项目:https://codesandbox.io/s/react-leaflet-editable-z7tnq?file=/src/App.js

link 到 react-leaflet-editable : https://www.npmjs.com/package/react-leaflet-editable

PS:您可以将旁边的 react-leaflet 版本切换到 2.8.0 以查看行为。

感谢大家的支持

refuseEffect结合使用,以获取react-leaflet v.2.x中的地图实例。通过这种方式,您可以模仿 whenCreated 在版本 3.x

中的作用
const [map, setMap] = React.useState();
const mapRef = useRef();

useEffect(() => {
    if (!mapRef.current) return;

    setMap(mapRef.current.leafletElement);
  }, []);


<ReactLeafletEditable ref={editRef} map={map}>
  <button onClick={editPolygon} className="editable-btn">
    Create Polygon
  </button>
  <Map
   style={{
   height: "700px",
       backgroundColor: "",
       flexGrow: "1",
       cursor: `10`
   }}
   ref={mapRef}
 ...

Demo