这是一个通用的JS问题。
在 React-leaflet 中,我想通过回调来处理事件。被调用的函数获取调用方(事件)上下文,该上下文可用于执行类似 this.getZoom() 的操作。
onMoveend={this.moveend}
moveend(e){
// e is the event target
var zoomText = this.getZoom();
// this.setState({zoomText: zoomText}); <-- "this" is the map object, not the my React component.
}
问题在于同时我需要反应元素上下文来更新状态并调用其他方法。
要实现"this.getZoom()",不应绑定回调,以实现"this.setState(...)"我需要将回调绑定到"this"。
但是如何将调用方和回调上下文作为变量传递给回调呢?
或者这种类型的问题可以通过另一种方式解决?
请参阅此jsfiddle:https://jsfiddle.net/nf8k23s7/1/
>e.target
已经是 Leaflet 元素。
因此,您可以使用:
moveend(e){
var zoomText = e.target.getZoom();
this.setState({zoomText: zoomText});
}
并且不要忘记绑定:
<Map center={position} zoom={this.state.zoom} onMoveend={this.moveend.bind(this)}>
更新了你的小提琴:https://jsfiddle.net/mrlew/nf8k23s7/2/
你也可以使用 => 箭头函数来绑定这个
moveend = (e) => {
var zoomText = e.target.getZoom();
this.setState({zoomText: zoomText});
}
<Map center={position} zoom={this.state.zoom} onMoveend={this.moveend}>