【发布时间】:2019-07-02 06:43:48
【问题描述】:
我使用带有自定义信息框的 Bing 地图。信息框还包含我想要执行关闭功能的自定义关闭图标。 我已经尝试了多种方法,但是没有执行 clearInfoBox 函数。
clearInfoBox() {
console.log("test");
}
var infoboxTemplate =
`<div style="margin-top:0px; margin-left:20px;">
<a href="javascript:void(0)" onClick="{this.clearInfoBox}"><img style="float: right;" src="${closeIcon}"/></a>
</div>`
this.centerOfSearchInfoBox = new window.Microsoft.Maps.Infobox(new window.Microsoft.Maps.Location(this.centerOfSearch.latitude, this.centerOfSearch.longitude), {
htmlContent: infoboxTemplate,
});
this.centerOfSearchInfoBox.setMap(map);
【问题讨论】:
-
点击关闭图标时如何调用函数
clearInfoBox()的问题是您尝试从this.clearCenterOfSearchInfoBox调用的函数吗?如果是这样,正常的问题是你没有绑定this.clearCenterOfSearchInfoBox到这个,所以onClick中的this是html元素而不是你的对象 -
抱歉是复制过去的错误我想在点击关闭图标时调用 clearInfoBox()
-
由于您使用
this,我假设您正在上课。在构造函数中,您需要添加this.clearInfoBox = this.clearInfoBox.bind(this)或将onClick更改为onClick="{this.clearInfoBox.bind(this)}"以在事件中获得对正确this的引用 -
方法默认不绑定。如果忘记绑定 this.clearInfoBox 并将其传递给 onClick,则在实际调用该函数时 this 将是未定义的。
-
是的,我正在上课。当我尝试
onClick="{this.clearInfoBox.bind(this)}时,我得到Cannot read property 'bind' of undefined at HTMLAnchorElement.onclick,当我尝试在构造函数中绑定它时,例如this.clearInfoBox.bind(this);然后调用它:onClick="{this.clearInfoBox}什么都没有发生
标签: javascript html reactjs bing-maps