我试图在每次点击地图时点击的地方显示一个弹出窗口(只需要显示一个弹出窗口)。
它第一次有效,但任何时候我点击之后都会赢得
。import React, { Component, createRef } from 'react';
import { Map as LeafletMap, TileLayer, Marker,Popup } from 'react-leaflet';
const newPopup = props => (
<Popup position={props.newCoords}>
<h1>You clicked here</h1>
</Popup>
);
export default class Map extends Component {
mapRef = createRef()
handleClick (e) {
const coords = this.mapRef.current.leafletElement.mouseEventToLatLng(e.originalEvent);
console.log(coords);
this.setState({
...this.state,
showNewPopup:true,
newName:"",
newCoords:coords
})
}
constructor() {
super()
this.state = {
lat: 52.369730195560706,
lng: 4.901275634765625,
zoom: 10,
showNewPopup:false,
newName:"",
newCoords:{lat:0,lng:0}
}
}
render() {
const position = [this.state.lat, this.state.lng];
return (
<LeafletMap
center={position}
zoom={this.state.zoom}
style={{width:"100%",height:"100%"}}
onClick={(e)=>this.handleClick(e)}
ref={this.mapRef}
>
<TileLayer
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url='http://{s}.tile.osm.org/{z}/{x}/{y}.png'
/>
{
(this.state.showNewPopup)
? newPopup(this.state)
: ""
}
</LeafletMap>
);
}
}
弹出窗口无法扩展,当您尝试出现错误时:
TypeError:超级表达式必须为null或函数,而不是对象
class MyPopup extends Popup {
}
const newPopup = props => (
<MyPopup position={props.newCoords}>
<h1>You clicked here</h1>
</MyPopup>
);
可能是因为this
export default withLeaflet(Popup)
试图包装组件并获取传单
的引用class NewPopup extends Component {
popRef = createRef()
componentDidUpdate(prevProps, prevState, snapshot) {
console.log("lll",prevProps.position,this.props.position);
this.popRef.current.leafletElement.openPopup(this.props.position);
// this.popRef.current.leafletElement.update();
// this.popRef.current.leafletElement.bringToFront();
// debugger;
}
render() {
return (
<div>
<Popup position={this.props.position} ref={this.popRef}>
<h1>You clicked here</h1>
</Popup>
</div>
);
}
};
没有错误但是相同的行为,在第一次点击后永远不会打开弹出窗口。
package.json中的依赖项:
"dependencies": {
"leaflet": "^1.3.0",
"react": "^16.4.1",
"react-dom": "^16.4.1",
"react-leaflet": "^2.0.0-rc.1",
"react-scripts": "1.1.4"
},