简体   繁体   中英

Parsing functions into dangerouslysetinnerhtml

I've currently go an issue with dangerouslysetinnerhtml. I'm trying to allow people to edit sections via a js document in react, and these edits appear in a form of a string. eg a person could parse the following as a string within the js file:

let html = `<div onClick="(input)=>{console.log(input)}">Click me</div>`

And in my code I'd like to display it as:

<div dangerouslySetInnerHTML={{ __html: html }}></div>;

The div appears just fine, but the 'onClick' function doesn't fire. I've seen recommendations to use HTML Parser, but that's not an option as I'm restricted from using external libraries in this case. Does anyone have any suggestions on how this should work?

Thanks!

You can do this way if you really need to.

let html = '<div onclick="console.log(this)">Click me</div>';

And same as you have done in your code.

<div dangerouslySetInnerHTML={{ __html: html }}></div>;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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