Handling onClick of a tag inside of dangerousl

2019-08-05 05:56发布

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.

0条回答
登录 后发表回答