gpt4 book ai didi

javascript - 自定义字体未加载到 Material UI 的自定义主题上

转载 作者:行者123 更新时间:2023-11-27 22:53:01 24 4
gpt4 key购买 nike

我在我的 React 网络应用程序中使用自定义字体。所以我写了这段代码:

import React, { FunctionComponent } from 'react'
import { createMuiTheme, MuiThemeProvider } from '@material-ui/core/styles'
import SofiaProLightTtf from '../../assets/font/sofia-pro-light.ttf'
import SofiaProTtf from '../../assets/font/sofia-pro-regular.ttf'

const sofiaPro = {
fontFamily: 'Sofia Pro',
fontStyle: 'normal',
fontWeight: 100,
src: `url(${SofiaProTtf})`
}

const sofiaProLight = {
fontFamily: 'Sofia Pro Light',
fontStyle: 'normal',
fontWeight: 100,
src: `url(${SofiaProLightTtf})`
}

const theme = createMuiTheme({
typography: {
fontFamily: 'Sofia Pro',
body1: {
fontFamily: 'Sofia Pro Light'
}
},
overrides: {
MuiCssBaseline: {
'@global': {
'@font-face': [sofiaPro, sofiaProLight]
}
}
}
})

const Theme: FunctionComponent = ({ children }) => (
<MuiThemeProvider theme={theme}>{ children }</MuiThemeProvider>
)

export default Theme

但它不起作用。所以我尝试使用纯 CSS 自定义字体。

我找到了一个解决方法,即删除 createMuiTheme 中的 overrides 属性并使用此 CSS:

<style>
@font-face {
font-family: 'Sofia Pro';
font-style: normal;
font-weight: 100;
src: url("/65e0f064b96a52b92f7293b673054b0b.ttf");
}

@font-face {
font-family: 'Sofia Pro Light';
font-style: normal;
font-weight: 100;
src: url("/d15399628129cc8121c08073df25f0dd.ttf");
}
</style>

但这是一个非常糟糕的解决方法……是否有更好的解决方案,特定于使用 Material UI 的元素?我在 createMuiTheme 上做错了吗?

最佳答案

// Best solution for production use.
// npm install @fontsource/exo

// Then you can import it in your entry point like this:
import '@fontsource/roboto/300.css';

// Then, config theme:
const theme = createTheme({
typography: {
fontFamily: 'Exo, sans-serif',
},
})

// in entry file(index.css/app.css)
body { font-family: "Exo", sans-serif; }

关于javascript - 自定义字体未加载到 Material UI 的自定义主题上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59368039/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com