我在React Web应用程序中使用自定义字体。所以我写了这段代码:
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自定义字体。
我找到了一种解决方法,并使用此CSS删除了overrides
中的createMuiTheme
属性:
<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
上做错了吗?
答案 0 :(得分:0)
首先,您需要将Webpack配置为使用字体或使用链接或CDN来配置字体,在将Webpack配置为处理字体或使用CDN之后,您可以转到theme.js并添加字体,以便可以使用在全球范围内
import RalewayWoff2 from './fonts/Raleway-Regular.woff2';
const raleway = {
fontFamily: 'Raleway',
fontStyle: 'normal',
fontDisplay: 'swap',
fontWeight: 400,
src: `
local('Raleway'),
local('Raleway-Regular'),
url(${RalewayWoff2}) format('woff2')
`,
unicodeRange: 'U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF',
};
在主题中像这样使用cssbaseline
const theme = createMuiTheme({
typography: {
fontFamily: 'Raleway, Arial',
},
overrides: {
MuiCssBaseline: {
'@global': {
'@font-face': [raleway],
},
},
},
});
我从文档中获得