首页 > 解决方案 > React - 如何将 GlobalStyles 用于带有情感的 Google 字体

问题描述

我正在使用 Emotion,我css-in-js和我都承认,我对它还很陌生。我花了1+。小时,弄清楚如何在我的整个应用程序中注入全局样式并添加谷歌字体。

我试过了:

有人可以给我一个工作的例子吗?我想要。在 JS 中学习 CSS,但这变得很奇怪。这么多时间,为了这么简单的事情。

标签: cssreactjstypescriptemotioncss-in-js

解决方案


我认为有两种方法可以做到:

  • 使用injectGlobal导出自emotion
import { injectGlobal } from 'emotion'

injectGlobal`
  @font-face {
    font-family: 'Patrick Hand SC';
    font-style: normal;
    font-weight: 400;
    src: local('Patrick Hand SC'),
      local('PatrickHandSC-Regular'),
      url(https://fonts.gstatic.com/s/patrickhandsc/v4/OYFWCgfCR-7uHIovjUZXsZ71Uis0Qeb9Gqo8IZV7ckE.woff2)
        format('woff2');
    unicode-range: U+0100-024f, U+1-1eff,
      U+20a0-20ab, U+20ad-20cf, U+2c60-2c7f,
      U+A720-A7FF;
  }
`
  • 使用Global来自@emotion/core
import { Global, css } from '@emotion/core'

function App() {
  return (
   <div>
    <Global styles={
      css`
        @font-face {
          font-family: 'Patrick Hand SC';
          font-style: normal;
          font-weight: 400;
          src: local('Patrick Hand SC'),
            local('PatrickHandSC-Regular'),
            url(https://fonts.gstatic.com/s/patrickhandsc/v4/OYFWCgfCR-7uHIovjUZXsZ71Uis0Qeb9Gqo8IZV7ckE.woff2)
              format('woff2');
          unicode-range: U+0100-024f, U+1-1eff,
          U+20a0-20ab, U+20ad-20cf, U+2c60-2c7f,
          U+A720-A7FF;
        }
       `
      }
    />
    // Others
   </div>
 )
}


推荐阅读