处理点击<a> tag inside of dangerouslySetInnerHTML/regular html

时间:2017-11-15 00:18:04

标签: javascript reactjs electron

I am currently writing a reddit client inside of ReactJS plus electron. I am simply doing this to understand apis better and to understand programming a large scale program. However I am becoming stuck when trying to render markdown. I have imported markdown to jsx libraries but none of them (unless I am using them wrong) have allowed me to properly convert the reddit markdown into a component I can work with.

For example from the reddit api, I receive a comment like this: Hi mi name is John Doe, and I want you guys to check out [Reddit]( http://www.reddit.com)也不要害怕查看[Google](http://www.google.com

现在我尝试使用将markdown转换为jsx的npm模块,这样可以生成markdown,但是我需要能够与onClick方法进行交互。很简单,因为它在电子窗口中运行,导航整个浏览器窗口将离开我的程序。目前我使用以下代码,但这非常慢,并且调用webview超过100次。

...
// On click of an a, this gets called a couple hundred times. :(
componentDidMount() {
var self = this;
$('.linkHandler a').click(function (e) {
  e.preventDefault();
  // Opens my own custom electron webview
  self.props.loadURL(e.target.href)
})}
...
render(){
return(
     <div className="linkHandler">
         {<ReactMarkdown source={comment.body} />}
</div>
)
}

}

我只想在我的markdown中为所有标记添加onClick处理程序。 Reddit也提供了降价的html,但是我还是在同一个地方。使用html版本我也尝试了以下操作:

onClick(){
    console.log('onClick Called');
}
...
getHTMl(){
    // Quickly tpyed this from memory, just keep in mind the original replaced every <a with <a onClick="" 
    return comment.body_html.replace(/<a/g,'<a onClick="' + this.onClick + '"');
}
...
render(){
return(
     <div setInnerHTMLDangerously={{"__html":this.getHTML()}}
)
}



  }

尝试向onClick添加(),但在单击按钮之前会调用它(100次)。现在的方式是,它会在控制台中返回错误:null引用(或类似的东西)。

0 个答案:

没有答案