如何解决如何在Mapbox弹出窗口中的onClick上调用函数?
对于Javascript,React,Mapbox以及我用来构建该项目的所有东西,我都是新手。我和我的搭档正在使用React前端和Rails后端。我们尚未使用Redux,Hook或Jquery。该应用程序是一个基于地图的网站,可让您单击纽约市的一栋历史建筑,查看该建筑的信息,并将该建筑最终添加到访问列表中。
我们能够呈现被单击的特定建筑物的信息,然后使用setHTML()将信息填充到Mapbox GL Popup中。在setHTML内部,我们创建了一个按钮,并试图使该按钮运行通过props传递的函数。
点击有效,我们已登录控制台,并能够设置警报以在点击时弹出。尝试从props调用函数时遇到的错误是“无法读取undefined的props”。我们尝试在组件内部创建函数,而不是通过props向下传递它没有用。我们认为正在发生的事情是onClick位于Popup函数内部,因此它无法识别Map组件的属性,也无法识别Map组件内部的功能。
反正从Popup组件中调用函数吗?
const map = new mapboxgl.Map({
container: this.mapContainer,style: this.style(),center: [this.state.lng,this.state.lat],zoom: this.state.zoom,maxZoom: 18,minZoom: 10,pitch: this.state.pitch,bearing: this.state.bearing,});
// Setting state to match user moving around the map
map.on("move",() => {
this.setState({
lng: map.getCenter().lng.toFixed(4),lat: map.getCenter().lat.toFixed(4),zoom: map.getZoom().toFixed(2),pitch: map.getPitch().toFixed(2),bearing: map.getBearing().toFixed(2),});
});
// Add polygons over buildings
map.on("load",function () {
// Add a source for the state polygons.
map.addSource("buildings",{
type: "geojson",data:
buildingUrl,});
// Add a layer showing the state polygons.
map.addLayer({
id: "username.styleid",type: "fill",source: "buildings",paint: {
"fill-color": "rgba(31,146,239,0.4)","fill-outline-color": "rgba(145,145,1)",},});
// When a click event occurs on a feature in the buildings layer,open a popup at the
// location of the click,with description HTML from its properties.
map.on("click","username.styleid",function (e) {
new mapboxgl.Popup()
.setLngLat(e.lngLat)
.setHTML(
"<strong>Developer: </strong>" +
e.features[0].properties.own_devel +
"<br><strong>Build Type: </strong></br>" +
e.features[0].properties.build_type +
"<br><strong>Architect: </strong></br>" +
e.features[0].properties.arch_build +
"<br><strong>Style: </strong></br>" +
e.features[0].properties.style_prim +
"<br><strong>Materials: </strong></br>" +
e.features[0].properties.mat_prim +
" & " +
e.features[0].properties.mat_sec +
"<br><strong>Build Date: </strong></br>" +
e.features[0].properties.date_combo +
"<br><strong>Original Use: </strong></br>" +
e.features[0].properties.use_orig +
"<br><strong>Borough: </strong></br>" +
e.features[0].properties.borough +
"<br><strong>Historical District: </strong></br>" +
e.features[0].properties.hist_dist +
"<br><strong>Address: </strong></br>" +
e.features[0].properties.des_addres +
`<br><button class="visit-button" onClick='{console.log("I was clicked")}'</button>Add to Visit List</button></br>`
)
.addTo(map);
});
最后几行是我们调用onClick的地方。预先感谢!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。