Javascript 当事件处理程序已绑定时,如何获取正在拖动的标记?
当处理程序是绑定函数时,是否有方法确定要拖动哪个Javascript 当事件处理程序已绑定时,如何获取正在拖动的标记?,javascript,reactjs,google-maps,google-maps-markers,Javascript,Reactjs,Google Maps,Google Maps Markers,当处理程序是绑定函数时,是否有方法确定要拖动哪个标记?下面是我的react组件的一个片段: constructor() { this.handleMarkerMove = this.handleMarkerMove.bind(this); } createMarker() { const marker = new google.maps.Marker({...}); google.maps.event.addListener(marker, "dragend", this
标记
?下面是我的react组件的一个片段:
constructor() {
this.handleMarkerMove = this.handleMarkerMove.bind(this);
}
createMarker() {
const marker = new google.maps.Marker({...});
google.maps.event.addListener(marker, "dragend", this.handleMarkerMove);
}
handleMarkerMove(e) {
const latitude = e.latLng.lat();
const longitude = e.latLng.lng();
const theMarker = ???
// this = the class when .bind(this) registered in constructor
}
如果我不使用this.handleMarkerMove=this.handleMarkerMove.bind(this)
我将丢失对this
的引用,这就是谷歌地图发送标记的方式
有没有办法在不创建嵌套函数的情况下将这个
和标记
都添加到handleMarkerMove(e)
,但是有一个repo可能有助于将googlemaps
与react
集成。您不能使用.bind(this)
,因为this
关键字将引用类本身。最好的选择是使用嵌套函数,这没有什么错:-)
您还可以添加标记作为第二个参数:
const marker = new google.maps.Marker({...});
google.maps.event.addListener(marker, 'dragend', this.handleMarkerMove.bind(this, marker));
现在,您可以通过事件处理程序中的第二个参数访问marker对象:
handleMarkerMove(e, marker) {...}
我希望这是可能的。
handleMarkerMove(e, marker) {...}