事件处理程序功能,如onload和onLocationfound均不起作用,功能尚未执行

问题描述 投票:0回答:1

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

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未被调用,这是我做错了吗?

reactjs react-hooks react-leaflet
1个回答
0
投票

没有可以传递onLocationfound组件的Map道具。参见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

Edit:我看了您的示例here,显然有一个onLocationfound事件使我感到困惑,因为在本机传单中称为locationFound,在react-leaflet中变成了onLocationFound。如果您想实现示例中的某项功能,则在地理位置发生后,它便可以工作,您将收到事件对象,并访问坐标,您需要像我前面提到的那样使用e.latlng。这是一个demo,可以现场观看。

检查文档的herehere

© www.soinside.com 2019 - 2024. All rights reserved.