问题描述
\frac{1}{10}
渲染为 1/1 0
如何显示 1/10?
解决方法
这是由于竞争条件。我在从 API 接收字符串并在 dom 中完全呈现之前调用了 MathJax.typeset();
。
我在 React 应用程序的上下文中使用 MathJax 来解释来自 API 的字符串。
以下是我现在所做的,基于 GiacoCorsiglia 的 Gist:Using MathJax v3 in React。
在index.html
中:
<script>
window.__MathJax_State__ = {
isReady: false,promise: new Promise(resolve => {
window.MathJax = {
// MathJax can be configured as desired in addition to these options.
startup: {
// Don't perform an initial typeset of the page when MathJax loads.
// Our React components will trigger typsetting as needed.
typeset: false,ready: () => {
// Do whatever MathJax would normally do at this point.
MathJax.startup.defaultReady();
// Set the flag and resolve the promise.
window.__MathJax_State__.isReady = true;
resolve();
}
}
};
})
};
</script>
<script src="https://polyfill.io/v3/polyfill.min.js?features=es6"></script>
<script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-svg.js"></script>
在呈现字符串的 component.jsx
中,我使用的是 useEffect()
:
useEffect(()=>{
// Avoid running this script if the MathJax library hasn't loaded yet.
if (!isMathJaxReady) {
// But trigger a re-render of this component once it is loaded.
__MathJax_State__.promise.then(() => setIsMathJaxReady(true));
return;
}
MathJax.typeset();
},[stringFromAPI,isMathJaxReady,setIsMathJaxReady]);