0

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

所以这里是下面的代码。它可以完美地工作,react-leaflet v.3.x但是当我切换到“2.8.0 版”时,它就可以正常工作了。

我尝试过的;Map被重命名为MapContainerin3.x所以我改变了它,但问题就变成了whenCreated={setMap}参数。我需要一种方法将其链接到ReactLeafletEditable. 或者至少我认为这是问题所在。

我希望我已经解释得很好。代码和链接如下。

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;

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

链接到react-leaflet-editablehttps ://www.npmjs.com/package/react-leaflet-editable

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

谢谢大家的支持

4

1 回答 1

1

在 react-leaflet v.2.x 中使用 aref和 auseEffect来获取地图实例。通过这种方式,您可以模仿whenCreated3.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}
 ...

演示

于 2021-05-10T09:53:53.450 回答