问题描述
当用户在 ckeditor5 中设计内容时,我将数据作为字符串保存在数据库中。来自数据库记录的示例字符串:
<p>What is the result of following?</p><p><math xmlns="http://www.w3.org/1998/Math/MathML"><msqrt><mn>16</mn></msqrt><mo> </mo><mo>+</mo><mo> </mo><mfrac><mn>3</mn><mn>9</mn></mfrac><mo> </mo><mo>=</mo><mo> </mo><mo>?</mo></math></p>
我的问题是关于渲染 html。如果它不包含 'html-react-parser'
标签,我可以使用 <math/>
包完美解析整个 html 字符串。它没有解析 <math/>
标签,人们建议使用 'react-mathjax-preview'
包。
但是当我用它解析整个 html 字符串时,它解析得很好,但是在 ckeditor5 上创建的其他 html 标签看起来像纯文本。所以我决定使用“DomParser()”将字符串转换为html,然后在它的“childNodes”中循环搜索它是否有数学标签。然后我用 (parse()
或 <MathJax/>
)
import MathJax from 'react-mathjax-preview';
const MathjaxParser = ({ mString }) => {
return <MathJax id="math-preview" math={mString} />;
};
export default MathjaxParser;
.
import React from 'react';
import parse from 'html-react-parser';
import MathJax from 'app/components/MathjaxParser';
const Parser = ({ mString }) => {
const iparser = new DOMParser();
const parsedHtml = iparser.parseFromString(mString,'text/html');
const itemsArray = [];
if (!parsedHtml || !parsedHtml.body) return null;
parsedHtml.body.childNodes.forEach(item => {
let type = 'normal';
if (!item.outerHTML) return;
if (item.outerHTML.includes('xmlns="http://www.w3.org/1998/Math/MathML')) {
type = 'math';
}
itemsArray.push({ type,html: item.outerHTML });
});
return (
<div className="cursor-pointer">
{itemsArray.map((item,index) =>
item.type === 'math' ? (
<MathJax key={index} mString={item.html} />
) : (
<div key={index}>{parse(item.html)}</div>
)
)}
</div>
);
};
export default Parser;
在项目的任何地方,我都这样渲染:
import Parser from 'app/components/Parser';
..........
return ( <Parser mString={stringHTML} /> );
但我认为这是一种解决方法,我想问一下您建议的正确方法是什么?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)