18

我正在使用https://github.com/styled-components/styled-components

我正在尝试为需要@font-face. 我想确保每个组件都独立于它的上下文,所以我在每个组件上定义font-family样式。但是如果我injectGlobal在多个组件中使用,我会@font-face为同一种字体获得多个规则。

我是否应该在我的入口点组件中定义@font-face规则ThemeProvider并接受浏览器可能不会加载所需字体的事实?

4

4 回答 4

28

这正是我们制作injectGlobal. 如果您查看我们的文档,他们会说:

我们不鼓励使用它。每个应用最多使用一次,包含在一个文件中。这是一个逃生舱。仅将其用于罕见的@font-face定义或身体造型。

所以我要做的是创建一个名为的 JS 文件global-styles.js,其中包含以下代码:

// global-styles.js

import { injectGlobal } from 'styled-components';

injectGlobal`
  @font-face {
     font-family: 'My custom family';
     src: url('my-source.ttf');
  }
`

正如你所看到的,我们在这里所做的只是注入一些全局样式——在这种情况下@font-face。完成这项工作所需的最后一件事是将此文件导入您的主入口点:

// index.js

import './global-styles.js'

// More stuff here like ReactDOM.render(...)

这意味着你的 font-face 只被注入一次,但你的所有组件仍然可以使用font-family: 'My custom family'!

这样做会给你一个不可见文本的闪烁(FOIT),但这styled-components与 - 如果你使用香草 CSS 是一样的。要摆脱 FOIT,需要更高级的字体加载策略,而不仅仅是@font-faceing。

由于这与 无关styled-components,我强烈建议观看这两集前端中心以了解更多关于如何最好地做到这一点:“制作 Web 字体后备”“西方最快的 Web 字体加载器”

于 2017-03-20T09:22:16.673 回答
15

在 Chrome 中同一枚硬币的另一面:

injectGlobal如果使用例如 react-router,请不要在内部使用 @font-face 。您将在每条新加载的路线上重新绘制所有应用程序。这就是为什么: 在此处输入图像描述

在每条新路线上下载相同的字体文件。只要您在单独的.css文件中包含 font-face - 问题就会解决,如此 github 问题的最后一条评论中所述。

于 2018-05-04T11:42:02.033 回答
10

injectGlobal已被弃用。使用createGlobalStyle

import { createGlobalStyle } from 'styled-components'

export const GlobalStyle = createGlobalStyle`  
  body {
    font-family: 'Muli', sans-serif;

    h1 {
      font-weight: 800;
      font-size: 36px;

    p {
      font-size: 18px;
    }
  }
`;

然后你可以在你的 App.js 中使用它:

import { GlobalStyle } from './styles/global'

class App extends Component {
  render() {

    return (
      <ThemeProvider theme={theme}>
        <>
          <GlobalStyle/>
          <Container/>
        </>
      </ThemeProvider>

    )
  }
}
于 2019-03-05T22:24:17.753 回答
1

我同意

我重新加载

import { createGlobalStyle } from 'styled-components';
import { silver } from 'shared-components/themes/colors';

export default createGlobalStyle`
    @font-face {
        font-family: "Proxima Nova";
        font-style: normal;
        font-weight: 300;
        font-display: swap;
        src: url("/static/media/fonts/proxima_nova/ProximaNova_300.otf");
    }

并做出反应创建应用程序

于 2020-06-08T12:41:55.590 回答