当用户在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字符串不包括'html-react-parser'
标记,我就可以完美地使用它来解析整个html字符串。它没有解析<math/>
标记,人们建议使用'react-mathjax-preview'
包。
但是当我用它解析整个html字符串时,它解析得很完美,但是在CKEditor5上创建的其他html标记看起来像纯文本。因此,我决定用"DomParser()“将字符串转换为html,然后在其"childNodes”中循环搜索是否有数学标记。
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} /> );
但我认为这是一种解决办法,我想问一下,你建议的正确方式是什么?
发布于 2022-05-29 19:14:46
react mathjax预览版本- 2.1.3将解决此问题。
https://stackoverflow.com/questions/67986140
复制相似问题