Handling onClick of a <a> tag inside of dangerouslySetInnerHTML/regular html

依然范特西╮ 提交于 2019-12-24 09:29:48

问题


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) Also don't be afraid to check out [Google](http://www.google.com)

Now I have tried using npm modules that convert markdown into jsx, this works and will render the markdown, but I need to be able to interact with the onClick methods. Simple because this is running in an electron window, and navigating the whole browser window will navigate away from my program. Current I have it working with the following code, but this is very slow and calls the webview over 100 times.

...
// 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>
)
}

}

I just want to be able to add an onClick handler to all of the tags in my markdown. Reddit also supplies the html of the markdown already, but alas I am still in the same spot. With the html version I also tried doing the following:

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()}}
)
}



  }

Tried adding () to the onClick but it gets called (100s of times) before clicking the button. The way it is now, it returns error: null reference (or something like that) in the console on click.

来源:https://stackoverflow.com/questions/47297441/handling-onclick-of-a-a-tag-inside-of-dangerouslysetinnerhtml-regular-html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!