4

我正在尝试在利用 Emotion 及其Global component的 React 项目中使用本地托管的字体。此方法适用于网络字体,例如Google Fonts,但是当我下载相同的字体并尝试使用 将其作为本地.ttf文件应用时@font-face,我无法获得相同的结果。

这是重要的文件,App.js

import React from "react";

import { Global, css } from "@emotion/core";
import styled from "@emotion/styled";

const GlobalStyles = css`
  @import url("https://fonts.googleapis.com/css?family=Dancing+Script&display=swap");

  @font-face {
    font-family: "Local Font";
    src: url("fonts/DancingScript-Regular.ttf");
  }

  * {
    text-align: center;
  }
`;

const FromGoogle = styled.h1`
  font-family: "Dancing Script";
`;

const FromLocal = styled.h1`
  font-family: "Local Font";
`;

function App() {
  return (
    <div className="App">
      <Global styles={GlobalStyles} />
      <FromGoogle>This text's font family is from Google.</FromGoogle>
      <FromLocal>
        This text's font family should be the same, except it comes from a local
        font file, and it's not working.
      </FromLocal>
    </div>
  );
}

export default App;

出于某种原因,文本中的文本FromGoogle使用 Google 字体很好,而来自的文本FromLocal则没有。我的第一个想法是这是路径的问题,但如果是,我无法判断。

这是GitHub 上的完整项目。我使用了 Create React App,并删除了所有不相关的样板。

4

2 回答 2

2

在我的 Next.js 应用程序中,我对这些版本使用了情感:

"@emotion/react": "^11.1.1",
"@emotion/styled": "^11.0.0",

我的全球风格是:

export const GlobalStyles = () => (
    <Global
        styles={css`
            @font-face {
                font-family: 'Faustina';
                font-style: normal;
                font-weight: 700;
                src: local(''), 
                    url('/fonts/Faustina/Faustina.woff') format('woff'),
                    url('/fonts/Faustina/Faustina.ttf') format('truetype');
            }

            * {
                box-sizing: border-box;
                font-family: Faustina;
            }

            html,
            body {
                width: 100%;
                height: 100%;
                min-height: 100%;
                padding: 0;
                margin: 0;
            }
        `}
    />
);

我的字体在

project_root/public/fonts/Faustina

// explicitly
project_root/public/fonts/Faustina/Faustina-Bold.ttf
project_root/public/fonts/Faustina/Faustina-Bold.woff

为了查看字体更改,我需要重新启动开发服务器,例如yarn dev. 在重新启动之前,我遇到了同样的问题,即不显示字体(甚至在开发工具网络选项卡中下载)。

于 2020-12-01T10:59:11.340 回答
0

就我而言,解决方案与此答案相同。

我需要在导入的css文件中定义字体,index.html如下所示:

<link rel="stylesheet" type="text/css" href="/styles/fonts.css" />

然后,我能够在我的情感主题中引用字体系列名称并让它们正确加载。

于 2021-11-01T21:55:02.573 回答