【问题标题】:JS function not getting called inside string html in reactJS函数在反应中没有在字符串html中被调用
【发布时间】:2021-01-26 21:09:58
【问题描述】:

我正在使用字符串 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 将打开。现在我想在 infowindow 的点击上打开一个新窗口。提前致谢!

【问题讨论】:

  • 您的模板文字将函数转换为字符串,它不引用函数。您必须以不使用字符串的方式设置内容。 (我不知道infowindow 所以我不知道那会是什么。)
  • “我正在使用字符串 html”——不要。你正在使用反应。使其成为适当的组件。从 render() 方法返回一些 JSX。
  • 问题是它是根据场景的唯一方法。并且警报被调用并且外部 JS 变量也被显示在警报中。但功能不起作用。忽略infowindow,只是说明如何在字符串文字html中调用JS函数

标签: javascript html reactjs react-native infowindow


【解决方案1】:

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

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

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

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

【讨论】:

  • 也许你可以在 React 中使用 render() 函数来渲染 HTML,而不是在字符串上使用它。或者动态使用,你也可以使用嵌套组件。
  • @JohhnyDev 你不能混合 html 字符串并做出这样的反应。
  • 请问有什么例子吗?我也使用过组件方法,但 infowindow 只需要 html 字符串或节点作为内容。
猜你喜欢
  • 2020-07-30
  • 1970-01-01
  • 1970-01-01
  • 2020-05-31
  • 1970-01-01
  • 2020-05-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多