?
构造(道具){ 超(道具) this.state = { selActive:4, 载入:false, MAPINFO </跨度> :’’ } this.onScriptLoad = this.onScriptLoad.bind(this) this.dataHandler - 我在哪里添加我的设置。 //然而,这回归了HOVER的错误 this.setState({ MAPINFO </跨度> :event.feature.countryNL}) });}
鈥
首先,我不建议您使用匿名函数设置为事件侦听器,因为在这种情况下您将无法 removeEventListener 或类似的东西(可能,因为它不清楚,是什么 map 这里)。
removeEventListener
map
第二件事是你不应该约束你的 dataHandler ,因为它已经是一个箭头功能,所以没有问题 this 在 - 的里面 dataHandler 上下文。你应该绑定的东西是你的手动事件监听器。所以结果代码应如下所示:
dataHandler
this
constructor(props){ super(props) this.state = { selActive: 4, loaded: false, mapInfo: '' } this.onScriptLoad = this.onScriptLoad.bind(this) this.dataHandler = this.dataHandler.bind(this) this.handleMouseOver = this.handleMouseOver.bind(this) } dataHandler = (getJson) => { fetch(getJson) .then(response => response.json()) .then(featureCollection => dataLayer = map.data.addGeoJson(featureCollection) ); map.data.addListener('mouseover', this.handleMouseOver); } handleMouseOver(event) { map.data.revertStyle(); map.data.overrideStyle(event.feature, {fillColor: 'blue'}); this.setState({mapInfo: event.feature.countryNL}) }
或者,使用箭头功能,自动绑定:
constructor(props){ super(props) this.state = { selActive: 4, loaded: false, mapInfo: '' } this.onScriptLoad = this.onScriptLoad.bind(this) this.dataHandler = this.dataHandler.bind(this) } dataHandler = (getJson) => { fetch(getJson) .then(response => response.json()) .then(featureCollection => dataLayer = map.data.addGeoJson(featureCollection) ); map.data.addListener('mouseover', this.handleMouseOver); } handleMouseOver = (event) => { map.data.revertStyle(); map.data.overrideStyle(event.feature, {fillColor: 'blue'}); this.setState({mapInfo: event.feature.countryNL}) }
希望对你有帮助! :)
在JavaScript中 this 总是指我们正在执行的函数的“所有者”,或者更确切地说,指向函数是其方法的对象。 请改用箭头功能。 箭头功能没有自己的功能 this/super/arguments 捆绑。它从其父词法范围继承它们。
this/super/arguments
map.data.addListener('mouseover', (event) => { map.data.revertStyle(); map.data.overrideStyle(event.feature, {fillColor: 'blue'}); // THIS IS WHERE I ADD MY SETSTATE. // HOWEVER, THIS RETURNS AN ERROR ON HOVER this.setState({mapInfo: event.feature.countryNL}) });
参考:
this 正常函数内部或者指向全局对象或当前实例(在通过 new )。然而 this 从外部范围捕获箭头函数内部。所以 this 在里面 addListener 回调是指全局对象( window )。要解决此问题,您有以下选择:
new
addListener
window
使用箭头功能:
运用 绑定功能 :
map.data.addListener('mouseover', function (event) { map.data.revertStyle(); map.data.overrideStyle(event.feature, {fillColor: 'blue'}); // THIS IS WHERE I ADD MY SETSTATE. // HOWEVER, THIS RETURNS AN ERROR ON HOVER this.setState({mapInfo: event.feature.countryNL}) }.bind(this));