[英]How to define a button and a function inside js (React)
onClick
function wherein when clicked on the map it shows the geocode information shown in the screenshot below through api.onClick
function ,其中当点击 map 时,它会显示下面屏幕截图中显示的地理编码信息 745A5DAEAZ70D106Function is not defined
Function is not defined
map.current.on('click', function(e) {
var coordinates = e.lngLat;
var lng = coordinates.lng;
var lat = coordinates.lat;
console.log(lat);
console.log(lng);
var d = fetch("https://api.mapbox.com/geocoding/v5/mapbox.places/" + lng + "," + lat + ".json?access_token={token_value}").then(response => response.json()).then(function(data) {
console.log(data)
var str = "<table border='1'><tr><td><center>Title</center></td><td><center>Content</center></td></tr>"
for (let i in data["features"]) {
str = str + "<tr><td style='padding:5px'>" + data["features"][i]["place_type"][0] + "</td><td style='padding:5px'>" + data["features"][i]["place_name"] + "</td></tr>"
}
str = str + "</table>"
// button
str = str + "<button onClick={myFunction}>Save</button>"
function myFunction() {
console.log('Saved pressed');
}
new mapboxgl.Popup()
.setLngLat(coordinates)
.setHTML(str)
.addTo(map.current)
});
console.log(d);
});
Fix code as below修复代码如下
// button
str += `<button onclick="myFunction()"}>Save</button>`;
I would guess the button (and the function name defined for it) are created with a different scope than where you have defined your function.我猜这个按钮(以及为它定义的 function 名称)是用不同于您定义 function 的 scope 创建的。 One of these might work:
其中之一可能有效:
const myFunction = () => console.log("saved pressed")
.const myFunction = () => console.log("saved pressed")
。this.myFunction
this.myFunction
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.