如何将传单打孔机与Reaction-传单3一起使用?

Reaction手册2.8.0中的旧方法是使用MapLayerwithLeaflet

但现在在Reaction传单中:

MapLayerwithLeaflet从版本3起不再推荐使用。

我正在努力掌握core:https://react-leaflet.js.org/docs/core-introduction

的文档

但以下命令不起作用,我收到

提供的对象不是层。

import React, { Component, useEffect } from "react";
import { useLeafletContext, leafletElement, createLayerComponent } from '@react-leaflet/core'
import { MapContainer, TileLayer, useMap } from "react-leaflet";
import Leaflet from "leaflet";
import "leaflet-routing-machine";

function Routing(props) {
    const context = useLeafletContext();
    useEffect(() => 
    {
      let routing = createLayerComponent(Leaflet.Routing.control(
      {
        waypoints: [
          Leaflet.latLng(33.52001088075479, 36.26829385757446),
          Leaflet.latLng(33.50546582848033, 36.29547681726967)
        ],
        lineOptions: {
          styles: [{ color: "#6FA1EC", weight: 4 }]
        },
        show: false,
        addWaypoints: false,
        routeWhileDragging: true,
        draggableWaypoints: true,
        fitSelectedRoutes: true,
        showAlternatives: false
      }), )
      const container = context.layerContainer || context.map
      container.addLayer(routing)

      return () => {
        container.removeLayer(routing)
      }
    })
  return null;
}


function MapComponent() {

  return (
      <MapContainer center={[33.5024, 36.2988]} zoom={14} >
        <TileLayer url="https://api.maptiler.com/maps/ch-swisstopo-lbm-dark/256/{z}/{x}/{y}.png?key=gR2UbhjBpXWL68Dc4a3f" />
        <Routing />
      </MapContainer>
    );
  }


export default MapComponent;

解决方案

您正在使用createLayerComponent,但布线机实际上是一个控件。使用createControlComponent

我还建议将其作为单独的自定义组件,如文档中所述,而不是将其放在useEffect中。医生很难办到。请随意阅读How to extend TileLayer component in react-leaflet v3?,了解这是否有助于理解如何使用Reaction-Leaplet v3制作自定义组件。

您可以这样做:

import L from "leaflet";
import { createControlComponent } from "@react-leaflet/core";
import "leaflet-routing-machine";

const createRoutineMachineLayer = (props) => {
  const instance = L.Routing.control({
    waypoints: [
      L.latLng(33.52001088075479, 36.26829385757446),
      L.latLng(33.50546582848033, 36.29547681726967)
    ],
    ...otherOptions
  });

  return instance;
};

const RoutingMachine = createControlComponent(createRoutineMachineLayer);

export default RoutingMachine;

Working Codesandbox

相关文章