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

我正在尝试使用 ReactTypeScript 使字体在 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;

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")
);

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


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

lxleesjs 回答:如何在带有 React 和 Typescript 的样式组件中使用 @font-face?

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

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

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

https://caniuse.com/woff2

本文链接:https://www.f2er.com/495.html

大家都在问