gpt4 book ai didi

javascript - 使用 React 或 jQuery 创建 DOMNode 以传递给谷歌地图 API

转载 作者:行者123 更新时间:2023-12-03 05:25:49 29 4
gpt4 key购买 nike

Google map 信息窗口 API 接受字符串或 DOMNode 作为参数。我可以使用 document.createElement() 生成 DOMNode,但随着我想要包含在其中的信息增加,它很快就会变成许多行代码。

这是我的 createInfoWindow 方法,例如:

  _createInfoWindow(id, location) {
...
let button = document.createElement('button')
button.appendChild(document.createTextNode('Add to Itenerary'))
google.maps.event.addDomListener(button, 'click', myFunction())
let content = document.createElement('div')
...
content.appendChild(button)
return new google.maps.InfoWindow({ content })
}

如果能够生成一个 DOMNode,我可以将其作为参数传递给不太冗长的 google map api,那就太好了。我正在用 React 编写这个应用程序,所以 React 是理想的选择,但无论有效 - 如果有一种方法可以在 jQuery 中生成 DOMNode,我也想知道。上面的示例缺少几行创建一堆 DOMElement 并将它们附加到内容的代码。

最佳答案

最好编写自己的 React 组件,其中包含您的内容,捕获对其 DOM 元素的引用,在 componentDidMount() 中实例化 google.maps.InfoWindow,并将其传递给 DOM 元素的引用。像这样的事情:

import React, {Component} from 'react'

class InfoWindow extends Component {
componentDidMount() {
this.infoWindowApi = new google.maps.InfoWindow({ content: this.infoDiv })
}

componentWillUnmount() {
this.infoWindowApi && this.infoWindowApi.close();
}

render () {
const { id, location, onButtonClick } = this.props;

return (
<div ref={ref => (this.infoDiv = ref)}>
<h2>Info</h2>
<p>${location}</p>
<button onClick={onButtonClick}>Add to Itenerary</button>
</div>
);
}
}

export default InfoWindow;

...在某些容器组件的其他地方:

<InfoWindow
id={someId}
location={theLocation}
onButtonClick={() => this.onInfoWindowClicked(location)}
/>

...或者如果您必须求助于 jQuery,只需创建一个快速内容 DIV 并传递到 InfoWindow:

var contentDiv = $('<div><h2>Info</h2><button>Add to Itinerary</button></div>').click(myFunction);

// [0] to extract first (and only) DOM element inside the jQuery selector
var infoWin = new google.maps.InfoWindow({ content: contentDiv[0] });

关于javascript - 使用 React 或 jQuery 创建 DOMNode 以传递给谷歌地图 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41148455/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com