简体   繁体   中英

How to parse Jsx String with expressions using dangerouslySetInnerHTML in React?

dangerouslySetInnerHTML is converting static html content properly but it is unable to evaluate expressions.

在此处输入图像描述

output:

在此处输入图像描述

How to evaluate expressions as well using dangerouslySetInnerHTML?

You can replace {some expression} with the evaluated content.

The example below uses string-math to turn the template html into the intended result. Your implementation would do this transformation for the dangerouslySetInnerHTML .

It uses a regex to find { something }. The .slice(1, -1) is needed to slice off the { and } .

 const templateStr = '<h2>Math --> {1 + 1}</h2>' document.getElementById('div').innerHTML = templateStr.replace(/{[^}]+}/g, str => stringMath(str.slice(1, -1)))
 <script src="https://cdn.jsdelivr.net/npm/string-math@1.2.2/string-math.js"></script> <div id='div'></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