【问题标题】:How do I change the font family of a reactjs button component?如何更改 reactjs 按钮组件的字体系列?
【发布时间】:2021-05-13 16:29:49
【问题描述】:

我一辈子都不知道如何更改包装在 reactjs 按钮组件中的文本的字体系列。我已经尝试过类覆盖,但它总是呈现为 Times New Roman。我还尝试将文本包装在 Typography 组件中并应用类覆盖,但这也不起作用。

这是我的按钮组件:

<Button
  variant="contained"
  className={classes.sideBarButtons}
  fullWidth
>
Some Text
</Button>

这是我使用 makeStyles 覆盖的类:

  sideBarButtons: {
    height: "25%",
    background: "#FF0000",
    borderRadius: 0,
    color: "white",
    paddingTop: "2em",
    paddingBottom: "2em",
    fontFamily: 'Roboto',
  },

【问题讨论】:

  • 您尝试使用标签“important”覆盖现有类,例如:fontFamily: 'Roboto !important',
  • Button组件从何而来?
  • @JoshBirdwell 它来自 material-ui/core npm 包。 link

标签: css reactjs fonts


【解决方案1】:

在 button.js 文件中:

import './button.css';

const Button = ({ children }) => (
    <button>{ children }</button>
);

然后在button.css文件中:

button {
   font-family: "Roboto"
}
  • { children } 是标签之间的文本。因此,在上面的代码中,{ children } 是从使用您的自定义按钮的文件中传入的。

例如,如果您在 SignIn.js 中使用您的自定义按钮:

import Button from './button';

<div>
     // "Sign In" is the { children }
     <Button type="submit">Sign In</Button>
</div>

【讨论】:

    【解决方案2】:

    比在App.js里面导入它

    import 'styles/font.css'

    【讨论】:

      【解决方案3】:

      您的样式表文件中似乎还有另一个具有高优先级的 css 规则,它使用 Times New Roman 为您的按钮设置样式。使用浏览器检查您的按钮元素以查看哪个 css 规则设置了 Times New Roman 字体并修复它。

      需要注意的是 MATERIAL-UI 的 Button 组件默认设置为 Roboto 的 font-family

      【讨论】:

        【解决方案4】:

        Material ui 使用内联样式,因此尝试覆盖它:

        <Button style={{ fontFamily: 'Roboto' }} label='Styled button' />
        

        <Button labelStyle={{ fontFamily: 'Roboto' }} label='Styled button' />
        

        【讨论】:

          猜你喜欢
          • 2015-12-25
          • 1970-01-01
          • 2015-07-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-06-27
          • 2013-07-12
          相关资源
          最近更新 更多