问题
I am trying to set up a react app for the following example https://react-leaflet.js.org/docs/example-events but cannot make it work due to compile errors. The same example in v2 works for me.
import React, {Component,useState} from 'react'
import { MapContainer, TileLayer, Marker,useMapEvents } from 'react-leaflet'
import Popup from 'react-leaflet-editable-popup'
function LocationMarker() {
const [position, setPosition] = useState(null)
const map = useMapEvents({
click() {
map.locate()
},
locationfound(e) {
setPosition(e.latlng)
map.flyTo(e.latlng, map.getZoom())
},
})
return position === null ? null : (
<Marker position={position} removable editable>
<Popup>You are here</Popup>
</Marker>
)
}
class Map extends Component{
render(){
return(
<MapContainer
center={{ lat: 51.505, lng: -0.09 }}
zoom={13}
scrollWheelZoom={false}
id="mapId">
<TileLayer
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<LocationMarker />
</MapContainer>
)
}
}
export default Map;
If i don't use a class i get render underfined error. If i try to use the function does not work. Any help would be appreciated
回答1:
I found the issue and it's related with
import Popup from 'react-leaflet-editable-popup'
This package is not compatible with react-leaflet v3
This minor edit was crashing my example.
without this edit it works
回答2:
try it
import React, {Component,useState} from 'react'
import { MapContainer, TileLayer, Marker,useMapEvents } from 'react-leaflet'
import Popup from 'react-leaflet-editable-popup'
function LocationMarker(props) {
const [position, setPosition] = useState(null)
const map = useMapEvents({
click() {
map.locate()
},
moveend() {
let center = map.getCenter();
let zoom = map.getZoom();
props.effectOn.setState(state => {
state.lat = center.lat;
state.lng = center.lng;
return { ...state }
});
},
locationfound(e) {
setPosition(e.latlng)
map.flyTo(e.latlng, map.getZoom())
},
})
return position === null ? null : (
<Marker position={position} removable editable>
<Popup>You are here</Popup>
</Marker>
)
}
class Map extends Component{
state = {
lat: 35.76218444303944,
lng: 51.33657932281495
};
render(){
return(
<MapContainer
center={[this.state.lat, this.state.lng]}
zoom={13}
scrollWheelZoom={false}
id="mapId">
<TileLayer
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<LocationMarker effectOn={this}/>
</MapContainer>
)
}
}
export default Map;
来源:https://stackoverflow.com/questions/64644619/cannot-configure-example-events-for-react-leaflet-v3-to-play