[英]Rendering HTML properly including math tags
當用戶在 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。 如果不包含<math/>
標簽,我可以使用'html-react-parser'
package 完美地解析整個 html 字符串。 它沒有解析<math/>
標簽,人們建議使用'react-mathjax-preview'
package。
但是當我用它解析整個 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} /> );
但我認為這是一種解決方法,我想問一下你建議的正確方法是什么?
react-mathjax-preview VERSION - 2.1.3 將解決這個問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.