简体   繁体   English

反应,通过dragonallySetInnerHTML在html中设置onClick

[英]React, setting onClick in html via dangerouslySetInnerHTML

I have a txt component that renders via dangerouslySetInnerHTML 我有一个通过危险地呈现的txt组件

It has this line: 它有这行:

lines[i] = lines[i].replace(capoRegex, "<div class='capo' onClick={this.toggleTranspose()}>$1</div>");

But when I click the element, I get this error: 但是,当我单击该元素时,出现此错误:

TypeError: this.toggleTranspose is not a function

How do I call my component's function from dangerouslySetInnerHTML ? 如何从危险地调用SetInnerHTML来调用组件的功能?

You can add it to the parent lifecycle method 您可以将其添加到父生命周期方法中

componentDidMount: function() {
    $('.capo').click(function(e){
        ...
    })
} 

have a look at this https://www.freecodecamp.org/forum/t/react-component-onclick/162316/3 看看这个https://www.freecodecamp.org/forum/t/react-component-onclick/162316/3

@victor zadorozhnyy's answer was the right direction. @victor zadorozhnyy的回答是正确的方向。 I didn't have jquery, and I needed to access the components setState method, so this was my final code: 我没有jquery,我需要访问组件setState方法,所以这是我的最终代码:

var component = this;
document.getElementById('capo').addEventListener('click', function(e) {
  transpose = parseInt(e.target.dataset["capo"]);
  component.setState({
    transpose: transpose
  });
}

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

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