【问题标题】:Adding custom font to MUI button in React + TypeScript在 React + TypeScript 中向 MUI 按钮添加自定义字体
【发布时间】:2022-08-18 18:30:00
【问题描述】:

我正在创建我的网站,并尝试在文本中添加字体。我尝试将 google 字体的链接添加到我的 Index.HTML 文件的 head 标记,以及将字体系列添加到 index.css。在此之后,我尝试在我的网站的样式表中创建一个 css 类,并在该类中添加字体。然后调用该类到mui按钮组件中的主网页文件。我不确定为什么没有将特定字体应用于文本。如果有人可以提供帮助,那就太好了。

<Stack direction=\'row\' spacing={1}>
      <div className=\'App-logo\'>
        <img src={Archit} alt=\'\' height={40} width={40} />


      </div>

      <Button className=\'button\' sx={{ color: \'bisque\' }}>=
        HOME
      </Button>

      <Divider className=\'button\' sx={{ color: \'beige\' }}>|</Divider>

      <Button sx={{ color: \'bisque\', font: \'Neucha\' }}>
        About
      </Button>

      <Divider className=\'button\' sx={{ color: \'bisque\' }}>|</Divider>

      <Button className=\'button\' sx={{ color: \'bisque\' }}>
        Projects
      </Button>

      <Divider className=\'button\' sx={{ color: \'bisque\' }}>|</Divider>

      <Button className=\'button\' sx={{ color: \'bisque\' }}>
        Activities
      </Button>

      <Divider className=\'button\' sx={{ color: \'bisque\' }}>|</Divider>

      <Button className=\'button\' sx={{ color: \'bisque\' }}>
        Gallery
      </Button>

      <Divider className=\'button\' sx={{ color: \'bisque\' }}>|</Divider>

      <Button className=\'button\' sx={{ color: \'bisque\' }}>
        Contact
      </Button>
    </Stack>

在分隔器 mui 组件上应用类名时,将应用样式但不适用于按钮元素。

我还附上了 index.html 文件和 index.css 文件以及我网站的样式表的屏幕截图。如果可以的话,请看一下并提供帮助。

App.css

index.html

index.css

  • 当您检查 Button 时,您是否看到是否被其他内容覆盖?如果您希望所有按钮都具有相同的字体,那么我建议您考虑将其添加到您的主题中。如果您对此解决方案感兴趣并且需要它的代码,请告诉我。谢谢
  • 嘿,Akis,你所说的对我来说很有意义,但我不确定如何实施。如果您可以共享代码/方法会很棒吗?

标签: css reactjs typescript material-ui frontend


【解决方案1】:

使用主题的一种方式,你可以这样做。

安装你的字体,在你的package.json 你应该看到类似"typeface-montserrat": "^1.1.13", 然后创建一个主题文件(用你的字体系列替换字体'Monserat'):

主题.jsx

import { createTheme } from '@mui/material/styles';

export const theme = createTheme({
  typography: {
    // fontFamily: ['Montserrat', 'serif'].join(','), Uncomment if you want all the typography to inherit this font.
    button: {
      fontFamily: ['Montserrat', 'serif'].join(','),
      fontSize: 16,
      fontWeight: 400,
    },
  }
});

在您的 App.jsx 文件中:

应用程序.jsx

import { ThemeProvider } from '@mui/material/styles';
...
const App = () => (
  <ThemeProvider theme={theme}>          
    <Button>Test button</Button>            
  </ThemeProvider>
);

有了上面所有的 Buttons 将继承在选定的字体系列中(不要忘记替换为您要使用的字体系列)。如果您希望所有排版都继承此字体系列,请使用我的 cmets 取消注释上面的行。让我知道它是否有帮助。

【讨论】:

    猜你喜欢
    • 2020-06-11
    • 1970-01-01
    • 1970-01-01
    • 2020-03-13
    • 2011-06-09
    • 2018-01-31
    • 1970-01-01
    • 2023-01-19
    • 1970-01-01
    相关资源
    最近更新 更多