如何使用 react-leaflet 显示我的搜索栏?

How can I do to display my search bar using react-leaflet?

我正在尝试使用 react-leaflet 库,所以我创建了一个组件 SearchControl,但不幸的是它不起作用...

这是我的组件的代码:

import { useEffect } from "react";
import { useMap } from "react-leaflet";
import { GeoSearchControl } from "leaflet-geosearch";
import "react-leaflet-geosearch/lib/react-leaflet-geosearch.css";

const SearchControl = props => {
  const map = useMap();

  useEffect(() => {
    const searchControl = new GeoSearchControl({
      provider: props.provider,
      ...props
    });

    map.addControl(searchControl);
    return () => map.removeControl(searchControl);
  }, [props]);

  return null;
};
export default SearchControl;

但问题是我收到以下错误:_reactLeaflet.useMap is not a function

我该如何解决?

你可以在那里看到完整的代码:My code

非常感谢您的帮助!

您的 package.json 中的依赖项已过时。

将 react-leaflet 更改为使用 v3.2.0。
另外,您需要包含原始反应挂钩(用于 useEffect),因此反应至少应基于 v16.8.0 构建。

这是更新后的 package.json:

{
  "name": "react-leaflet",
  "version": "1.0.0",
  "description": "",
  "keywords": [],
  "main": "src/index.js",
  "dependencies": {
    "leaflet": "1.7.1",
    "react": "17.0.2",
    "react-dom": "17.0.2",
    "react-leaflet": "3.2.0",
    "react-leaflet-fullscreen": "1.0.1",
    "react-leaflet-geosearch": "0.3.0",
    "react-scripts": "4.0.3"
  },
  "devDependencies": {},
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  }
}

编辑:

除了注释之外,这是一个更新的 index.js,它使用 MapContainer 而不是 Map

import React from "react"; import ReactDOM from "react-dom"; import { MapContainer, TileLayer, Marker, Popup } from "react-leaflet"; import "./styles.css"; import { OpenStreetMapProvider } from "react-leaflet-geosearch"; import SearchControl from "./SearchControl";

const App = () => {   const prov = OpenStreetMapProvider();

  return (
    <div>
      <MapContainer center={[51.505, -0.091]} zoom={13}>
        <TileLayer
          attribution='&amp;copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
          url="https://{s}.tile.osm.org/{z}/{x}/{y}.png"
        />
        <SearchControl
          provider={prov}
          showMarker={true}
          showPopup={false}
          popupFormat={({ query, result }) => result.label}
          maxMarkers={3}
          retainZoomLevel={false}
          animateZoom={true}
          autoClose={false}
          searchLabel={"Enter address, please"}
          keepResult={true}
        />
      </MapContainer>
    </div>   ); };

const rootElement = document.getElementById("root"); ReactDOM.render(<App />, rootElement);