在使用 Material-UI(现在称为 MUI)时,你可以通过主题提供程序(ThemeProvider)来配置和应用多种字体。MUI 的主题系统非常灵活,允许你自定义各种样式,包括字体。
以下是一个示例,展示了如何通过 MUI 的主题提供程序来配置多种字体。
首先,确保你已经安装了 MUI 和相关的依赖项。
npm install @mui/material @emotion/react @emotion/styled
你可以创建一个自定义主题,并在其中定义多种字体。以下是一个示例,展示了如何在主题中配置多种字体。
import React from 'react';
import ReactDOM from 'react-dom';
import { ThemeProvider, createTheme } from '@mui/material/styles';
import Typography from '@mui/material/Typography';
import CssBaseline from '@mui/material/CssBaseline';
// 创建自定义主题
const theme = createTheme({
typography: {
fontFamily: 'Roboto, Arial, sans-serif',
h1: {
fontFamily: 'Georgia, serif',
},
h2: {
fontFamily: 'Courier New, monospace',
},
body1: {
fontFamily: 'Roboto, Arial, sans-serif',
},
// 你可以继续为其他变体定义字体
},
});
const App = () => (
<ThemeProvider theme={theme}>
<CssBaseline />
<div>
<Typography variant="h1">This is H1 with Georgia</Typography>
<Typography variant="h2">This is H2 with Courier New</Typography>
<Typography variant="body1">This is body1 with Roboto</Typography>
</div>
</ThemeProvider>
);
ReactDOM.render(<App />, document.getElementById('root'));
确保你已经在项目中引入了所需的字体。你可以通过在 index.html
中添加 <link>
标签来引入 Google Fonts,或者通过 CSS 文件引入本地字体。
在 public/index.html
文件中添加以下内容:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>React App</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap" />
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Georgia:300,400,500,700&display=swap" />
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Courier+New:300,400,500,700&display=swap" />
</head>
<body>
<div id="root"></div>
</body>
</html>
你也可以在 CSS 文件中引入本地字体:
@font-face {
font-family: 'MyCustomFont';
src: url('/path/to/font.woff2') format('woff2'),
url('/path/to/font.woff') format('woff');
font-weight: normal;
font-style: normal;
}
然后在主题中使用这个自定义字体:
const theme = createTheme({
typography: {
fontFamily: 'MyCustomFont, Arial, sans-serif',
// 其他配置
},
});
领取专属 10元无门槛券
手把手带您无忧上云