简体   繁体   English

如何在js中定义一个按钮和一个function(React)

[英]How to define a button and a function inside js (React)

  • I am using MapBox to render a map.我正在使用 MapBox 渲染 map。 I have made a onClick function wherein when clicked on the map it shows the geocode information shown in the screenshot below through api.我制作了一个onClick function ,其中当点击 map 时,它会显示下面屏幕截图中显示的地理编码信息 745A5DAEAZ70D106

在此处输入图像描述

  • Now what I want is to have a button below the table and when click on it I want it to execute a particular function, I have defined it but when clicked on it says Function is not defined现在我想要的是在表格下方有一个按钮,当点击它时,我希望它执行特定的 function,我已经定义了它,但是当点击它时说Function is not defined
  • Code代码
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:其中之一可能有效:

  1. Define your function as const myFunction = () => console.log("saved pressed") .将您的 function 定义为const myFunction = () => console.log("saved pressed")
  2. Try referencing your function as this.myFunction尝试将您的 function 引用为this.myFunction

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM