问题
I would like to create a custom component with react-leaflet that shows the actual position (x,y) of the mouse, but I don't know how to create it. I found react-leaflet-control
but it seems that it is not up to date, of course I readded the api documentation https://react-leaflet.js.org/docs/en/custom-components.html but I did not understand it :/
Can someone give me an exemple of a custom component please, juste a component that display "Hello world" whould be more than enought.
回答1:
As per documentation, to create a custom component the following steps are required:
1)extend one of the abstract classes provided by React-Leaflet
, for example:
class MapInfo extends MapControl {
//...
}
2)implement createLeafletElement (props: Object): Object
method to create the relevant Leaflet element instance, for example:
createLeafletElement(opts) {
const MapInfo = L.Control.extend({
onAdd: (map) => {
this.panelDiv = L.DomUtil.create('div', 'info');
return this.panelDiv;
}
});
return new MapInfo({ position: 'bottomleft' });
}
3) wrap your custom component using the withLeaflet()
HOC, for example:
export default withLeaflet(MapInfo);
The following example demonstrates how create a custom component to display the actual position (lat,lng)
of the mouse on map:
Demo
回答2:
@Vadim Gremyachev asnwer was very useful to me, but I had to spend some more hours with my debugger and react-leaflet's library. Finaly I successfully extended a CustomMarker
component from react-leaflet's MapLayer
abstract class. That's originally the base component which react-leaflet's Marker
extends from. The problem was that initially I had implemented a componentDidMount
method that shadows the base one. So in addition I had to call inside my method the following line as well.
super.componentDidMount()
That tells MapLayer
to attach this.reactLeaflet
as a layer to leaflet's map.
Entire code:
import React from 'react';
import { Marker as LeafletMarker } from 'leaflet';
import { MapLayer } from 'react-leaflet';
import { withLeaflet } from 'react-leaflet';
class CustomMarker extends MapLayer {
//Whatever leaflet element this function return it will be assigned to this.leafletElement property.
createLeafletElement(props) {
let options = this.getOptions(props);
const el = new LeafletMarker(props.position, options);
let layer = props.leaflet.layerContainer;
let map = props.leaflet.map;
return el;
}
updateLeafletElement(fromProps, toProps) {
if(fromProps.someProp != toProps.someProp){
//Modify this.leafletElement;
}
}
componentDidMount() {
super.componentDidMount();
let el = this.leafletElement
}
}
export default withLeaflet(CustomMarker);
You can also implement the render
method if your component expect to have some children. Check how they do it in react-leaflet's original components, like within Marker
in the example above.
来源:https://stackoverflow.com/questions/52012591/react-leaflet-create-a-custom-components