像 onload 和 onLocationfound 这样的事件处理程序函数不工作函数没有被执行

event handlers function like onload and onLocationfound are not working function is not being excecuted

我正在尝试使用以下代码获取当前用户位置:

const OSMap: React.FC = () => {
  const [mapState] = useState({ lat: 51.505, lng: -0.09, zoom: 13 })

  const handleLocationFound = event => {
    console.log('tesr', event.latLng)
  }

  return (
    <Map
      center={[mapState.lat, mapState.lng]}
      onLocationfound={handleLocationFound}
      zoom={mapState.zoom}
    >
      <TileLayer
        attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
        url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
      />
    </Map>
  )
}

没有调用 handleLocationFound 或 handleLoad 我做错了什么?

没有可以传递给 Map 组件的 onLocationfound 道具。参见 here

我猜你想要实现的是在地图上有一个 onClick 事件,并在你点击它时获取坐标。你可以这样实现:

const OSMap: React.FC = () => {
  const [mapState] = useState({ lat: 51.505, lng: -0.09, zoom: 13 })

  const handleLocationFound = event => {
    console.log('tesr', event.latlng)
  }

  return (
    <Map
      center={[mapState.lat, mapState.lng]}
      onClick={handleLocationFound}
      zoom={mapState.zoom}
    >
      <TileLayer
        attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
        url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
      />
    </Map>
  )
}

通过将 onLocationfound 替换为 onClick 并将 e.latLng 替换为 e.latlng

编辑:我查看了您的示例here and obviously there is an onLocationfound event which confused me as in native leaflet is called locationFound and becomes onLocationFound in react-leaflet. If you want to achieve sth like in the example it works once the geolocation takes place you receive the event object and to access the coords you need to take e.latlng as I mentioned before. Here is a demo 以实时查看它。

检查 here and here 文档