简体   繁体   English

如何在 React 中使用危险的 SetInnerHTML 解析 Jsx 字符串?

[英]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. dangerouslySetInnerHTML 正在正确转换 static html 内容,但它无法评估表达式。

在此处输入图像描述

output: output:

在此处输入图像描述

How to evaluate expressions as well using dangerouslySetInnerHTML?如何使用 dangerouslySetInnerHTML 评估表达式?

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.

相关问题 NextJS/JSX:如何在不使用危险的SetInnerHTML 的情况下插入动态生成的 JSX? - NextJS/JSX: How to insert dynamically generated JSX without using dangerouslySetInnerHTML? 在React中危险地渲染带有JSX表达式的HTML字符串SetInnerHTML() - Render HTML string w/JSX expression in React dangerouslySetInnerHTML() 如何将JSX组件与dangerouslySetInnerHTML结合使用 - How to combine JSX component with dangerouslySetInnerHTML 如何在 React 中使用 dangerouslySetInnerHTML 传递样式 - how to pass style using dangerouslySetInnerHTML in React React 使用预先确定的组件在字符串上添加 HTML 标签(替代危险的SetInnerHTML) - React add HTML tags on string using predetermined components (alternative to dangerouslySetInnerHTML ) 如何突出显示里面的字符串标记反应? 危险地设置InnerHTML - How to highlight string inside <code/> tag in react? dangerouslySetInnerHTML 使用 dangerouslySetInnerHTML 渲染内容时如何禁用 React 中的链接? - How to disable links in React when rendering content using dangerouslySetInnerHTML? React:如何用JSX连接字符串 - React: How to concatenate string with JSX JSX组件+ dangerouslySetInnerHTML? - JSX Component + dangerouslySetInnerHTML? 反应,我如何嵌入 <br/> 在jsx表达式中 - React, how do I embed <br/> in jsx expressions
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM