我使用IconMoon创建自定义图标字体。
在它生成的.html中,它可以完美运行。但是,当我尝试在我的React和Styled-Components项目中使用它时,图标并未显示,而是显示为HTML格式。
我的字体在路径中:src / assets / fonts / icons
很快,我正在尝试为我的字体创建一个类似于FontAwesome的组件,并且会发生这种情况:
我的组件:
import React from "react";
import styled from "styled-components";
const Tst = styled.i`
font-family: "spotify" !important;
font-style: normal;
font-weight: normal;
font-variant: normal;
text-transform: none;
line-height: 1;
::before {
content: "\e900";
color: red;
}
`;
const SaveFavorite = () => {
return <Tst />;
};
export default SaveFavorite;
我的全球风格:
import { createGlobalStyle } from "styled-components";
const GlobalStyle = createGlobalStyle`
@font-face {
font-family: "spotify";
font-weight: normal;
font-style: normal;
src: url("../assets/fonts/spotify.eot?") format("embedded-opentype"),
url("../assets/fonts/spotify.ttf?") format("truetype"),
url("../assets/fonts/spotify.woff?") format("woff"),
url("../assets/fonts/spotify.svg?") format("svg");
}
* {
box-sizing: border-box;
padding: 0;
margin: 0;
outline: 0;
}
body {
font-family: 'CircularSpUIv3T', sans-serif;
color: white;
text-rendering: optimizeLegibility !important;
-webkit-font-smoothing: antialiased !important;
-moz-osx-font-smoothing: grayscale !important;
user-select: none;
}
img {
width: 100%;
max-width: 100%;
height: auto;
}
`;
export default GlobalStyle;
答案 0 :(得分:0)
如果您查看由样式化组件生成的css,您会发现字体路径根本无法解析,它们正是您键入它们的方式。没有Babel的帮助,浏览器将无法在src
目录中找到相对路径,而现在您拥有这些路径的方式将按原样传递。
您有两种选择,尽管我不确定这两种方法是否都可以。
public
目录与任何旧的HTML页面一样,浏览器可以找到公共目录中的文件。在您的全局样式中,您将必须使用相对于public/index.html
的路径。
您的文件结构将类似于:
project
|-- public
|-- index.html
|-- fonts
|-- spotify.eot
|-- spotify.ttf
|-- spotify.woff
|-- spotify.svg
|-- src
|-- global.style.js
|-- (...)
还有您的global.style.js
:
const GlobalStyle = createGlobalStyle`
@font-face {
font-family: "spotify";
src: url("fonts/spotify.eot?") format("embedded-opentype"),
url("fonts/spotify.ttf?") format("truetype"),
url("fonts/spotify.woff?") format("woff"),
url("fonts/spotify.svg?") format("svg");
}
src
中,但让Babel为您解决路径要使Babel解析路径,我们需要将文件导入global.style.js
中,然后使用解析的路径而不是静态路径:
import SpotifyEOT from '../assets/fonts/spotify.eot';
// etc
const GlobalStyle = createGlobalStyle`
@font-face {
font-family: "spotify";
src: url(${SpotifyEOT}?) format("embedded-opentype"),
// [etc]
}
我不知道问号的实际用途,但我想您可以像我一样将其放置在解析的路径之后。