如何在 React 和 Typescript 的样式组件中使用 @font-face?

Leo*_*eon 1 css font-face typescript reactjs styled-components

React我正在尝试让字体与TypeScript和 一起使用styled-components

看起来GlobalStyle.ts如下:

import { createGlobalStyle } from "styled-components";

const GlobalStyle = createGlobalStyle`
   @font-face {
     font-family: 'Roboto';
     font-style: normal;
     font-weight: 300;
     src: url('./fonts/roboto-v27-latin-300.eot'); /* IE9 Compat Modes */
     src: local(''),
          url('./fonts/roboto-v27-latin-300.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
          url('./fonts/roboto-v27-latin-300.woff2') format('woff2'), /* Super Modern Browsers */
          url('./fonts/roboto-v27-latin-300.woff') format('woff'), /* Modern Browsers */
          url('./fonts/roboto-v27-latin-300.ttf') format('truetype'), /* Safari, Android, iOS */
          url('./fonts/roboto-v27-latin-300.svg#Roboto') format('svg'); /* Legacy iOS */
   }

   *{
        color: red;
        font-family: "Roboto";
   }
   `;

export default GlobalStyle;
Run Code Online (Sandbox Code Playgroud)

My index.tsx看起来像这样:

import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import GlobalStyle from "./GlobalStyle";

ReactDOM.render(
    <React.StrictMode>
        <GlobalStyle />
        <App />
    </React.StrictMode>,
    document.getElementById("root")
);

Run Code Online (Sandbox Code Playgroud)

我从两个文件中删除了一些在此上下文中不必要的行。这两个文件在目录中处于同一级别。字体文件全部下载到名为“fonts”的文件夹中


“正常”样式的工作方式类似于“颜色:红色;” 在GlobalStyles.ts。但是,我根本无法加载字体。有谁知道如何解决这一问题?如果您需要更多信息,请告诉我,我会提供!

Aar*_*nat 7

样式化的组件结构和语法看起来不错。

\n

Webfont 文件需要位于public外部文件夹中src(因为它们\xe2\x80\x99 不会像使用图像资源或静态 css 文件那样直接导入到组件中)。<style>指向字体 url 的 CSS 规则最终将与标签在 DOM 中插入的位置相关,而不是与 React 项目文件夹结构相关。所以您可能需要更新您的url因此,在移动字体后,

\n

另外,除非您确实需要支持旧版浏览器,否则您实际上只需要woff2格式。

\n

https://caniuse.com/woff2

\n