[英]How to parse Jsx String with expressions using dangerouslySetInnerHTML in React?
You can replace {some expression}
with the evaluated content.您可以将
{some expression}
替换为评估的内容。
The example below uses string-math
to turn the template html into the intended result.下面的示例使用
string-math
将模板 html 转换为预期结果。 Your implementation would do this transformation for the dangerouslySetInnerHTML
.您的实现将对
dangerouslySetInnerHTML
的SetInnerHTML 进行此转换。
It uses a regex to find { something }.它使用正则表达式来查找 { something }。 The
.slice(1, -1)
is needed to slice off the {
and }
.需要
.slice(1, -1)
来切掉{
和}
。
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.