我正在使用 MUI 库开发 React 应用程序,并面临动态设置字体系列的问题。目标是允许用户从配置器中选择字体,其中字体托管在远程服务器上(由于特定要求,不在项目文件中)。
这是我当前构建主题和获取字体的方法::
const buildTheme = () => {
/**
* Fetch data and store it in the state.
*
* src: url to the font stored on the server (EX: https://storage.com/documents/fonts/examplefont.ttf).
* cssValue: font-family value
*/
const {
fontData: { src, cssValue },
} = state;
return createTheme(getBaseTheme(cssValue), {
components: {
MuiCssBaseline: {
styleOverrides: {
'@font-face': {
fontFamily: [cssValue].join(','),
src: `url(${src})`,
},
},
},
},
});
};
// ThemeProvider setup
<ThemeProvider theme={buildTheme()}>
<CssBaseline />
{globalStyles}
{children}
</ThemeProvider>
通过此设置,@font-face 规则已正确添加到 styleOverrides,并且应用程序的版式设置似乎已正确配置。但是,字体并未在 UI 中呈现。
我还尝试了另一种方法,使用 useEffect 挂钩将元素附加到文档头,但这也不起作用:
useEffect(() => {
const link = document.createElement('link');
link.href = state.systemFontFamily.src;
link.rel = 'stylesheet';
document.head.appendChild(link);
}, [state.fontData]);
(不要因为这个电话向我扔西红柿,我就像萨尔萨舞课上的猫一样,在几个小时后没有任何进展的情况下对这件事一无所知)。
尽管做出了这些努力,但没有一个自托管字体能够渲染。控制台中没有 CORS 错误或其他相关消息。
我在这里缺少什么,如何在基于 MUI 的 React 应用程序中成功从服务器加载和应用字体?
答案:
Mui 改变了我们处理任何 @font-face 覆盖的方式。正确的(更新的)方法:
components: {
MuiCssBaseline: {
styleOverrides: `
@font-face {
font-family: ${name}; // "Fira Code"
src: url(${src}); // https://font-host.github.io/fira-code.woff2
}
`,
},
},
所以,不需要使用或任何呵呵😅😅