JS函数没有在React中的字符串html内部被调用

问题描述

我正在使用字符串html,其中有一个图像。我必须调用onclick函数。 Onclick功能有效,但仅用于警告。当我调用JS函数时,它不会被调用。我使用了this.bind,箭头功能和所有可能的方式,但没有结果。它处于反应状态,仅在此处粘贴相关代码

import pic1 from '../../assets/img/1.png'

class MapModule extends Component {
  _isMounted = false;
  constructor(props) {
    super(props);
    this.state = {
      id: null,redirect: false,store:props.latlng,toggleFlag: false
    };
    this.Toggle =  this.Toggle.bind(this);
  }
  
  Toggle () {
    alert('Clicked');
    
  }
  
  let content1 = `
        <div class="opacityEffect">
          <img width=100% onclick=${this.Toggle} src=${pic1}>
        </div>`;
        
  // This in event on infowindow for google maps
  marker.addListener('click',function () {
    map.setZoom(22);
    map.setTilt(45);
    infowindow.setContent(content1)
    infowindow.open(map,marker);
  });

PS:一切正常,有200行代码。打开地图标记信息窗口的onclick。现在,我想在信息窗口的Click上打开一个新窗口。预先感谢!

解决方法

正如我在您的代码中看到的那样,您使用了普通的HTML onclick事件来调用React函数。在React JS中,onclick事件的语法如下所示。

<button onClick={activateLasers}>
   Activate Lasers
</button>

据我观察,您需要在onclick中使用“ C”。当我第一次使用Riot.js时遇到了同样的问题,当我改成小写字母时,它就解决了。

我认为您不需要在React事件中使用“ this”。