我想将 Mathjax 集成到我的 nextjs 应用程序中。 我正在使用 nextjs 13 并使用 app dir 进行路由 我希望我的代码在服务器中呈现,这样当用户打开页面时不需要重新呈现。 我尝试阅读文档,但仍然缺乏信息。
我想要
Some inline equation $x^2-2x+5=0$ will render inline.
和Some display equation using duble dollar $$x^2-2x+5=0$$ will render display.
这是我的代码
import { mathjax } from 'mathjax-full/js/mathjax.js';
import { TeX } from 'mathjax-full/js/input/tex.js';
import { SVG } from 'mathjax-full/js/output/svg.js';
import { liteAdaptor } from 'mathjax-full/js/adaptors/liteAdaptor.js';
import { RegisterHTMLHandler } from 'mathjax-full/js/handlers/html.js';
const inputTex = 'Persamaan $c = \\pm\\sqrt{a^2 + b^2}$';
const adaptor = liteAdaptor();
RegisterHTMLHandler(adaptor);
const tex = new TeX();
const svg = new SVG();
const html = mathjax.document('', { InputJax: tex, OutputJax: svg });
// Mode inline
const nodeInline = html.convert(inputTex, { display: false });
const svgCodeInline = adaptor.outerHTML(nodeInline);
// Mode display
const nodeDisplay = html.convert(inputTex, { display: true });
const svgCodeDisplay = adaptor.outerHTML(nodeDisplay);
export default function page() {
return (
<>
<span dangerouslySetInnerHTML={{ __html: svgCodeInline }}></span>
<span dangerouslySetInnerHTML={{ __html: svgCodeDisplay }}></span>
</>
)
}
您可以使用此函数仅渲染 $$:
之间的方程export function RenderLatex(latex) {
let result = latex.split("");
let firstPos = null;
let firstFounded = false;
let returnString = latex;
for (let i = 0; i < latex.length; i++) {
if (latex[i] === "$" && !firstFounded) {
firstFounded = true;
firstPos = i;
}
if (firstFounded && i < 1 && firstPos === i - 1)
firstFounded = false;
else if (latex[i] === "$" && firstFounded && i !== firstPos) {
firstFounded = false;
result[firstPos] = ""
result[i] = ""
let firstPart = result.join("").slice(0, firstPos);
let secondPart = result.join("").slice(i, result.join("").length);
let addition = MathJax.tex2chtml((result.join("").substring(firstPos, i))).outerHTML;
return RenderLatex(firstPart + addition + " " + secondPart)
}
}
return returnString;