如何在React.js中使用Google字体?

问题描述 投票:57回答:8

我用React.js和webpack构建了一个网站。

我想在网页中使用Google字体,因此我将链接放在该部分中。

Google Fonts

<link href="https://fonts.googleapis.com/css?family=Bungee+Inline" rel="stylesheet">

And set CSS

body{
    font-family: 'Bungee Inline', cursive;
}

但是,它不起作用。

我怎么解决这个问题?

reactjs webpack google-font-api
8个回答
42
投票

在某种主要或第一个加载CSS文件中,只需:

@import url('https://fonts.googleapis.com/css?family=Source+Sans+Pro:regular,bold,italic&subset=latin,latin-ext');

您不需要包装任何类型的@ font-face等。您从Google的API中获得的响应已准备就绪,并允许您像平常一样使用字体系列。

然后在你的主要React app JavaScript中,在顶部放置如下内容:

import './assets/css/fonts.css';

我实际上做了一个app.css进口fonts.css与几个字体导入。只是为了组织(现在我知道我的所有字体都在哪里)。要记住的重要一点是先导入字体。

请记住,导入到React应用程序的任何组件都应在导入样式后导入。特别是如果这些组件也导入自己的样式。这样您就可以确定样式的顺序。这就是为什么最好在主文件的顶部导入字体(不要忘记检查你的最终捆绑的CSS文件,以仔细检查你是否遇到麻烦)。

在加载字体等时,您可以通过Google Font API来提高效率。请参阅官方文档:https://developers.google.com/fonts/docs/getting_started

编辑,注意:如果您正在处理“离线”应用程序,那么您可能确实需要下载字体并通过Webpack加载。


33
投票

打开你的样式表,即app.css,style.css(你有什么名字),没关系,只需打开样式表并粘贴这段代码

@import url('https://fonts.googleapis.com/css?family=Josefin+Sans');

并且不要忘记更改您想要的字体的URL,否则正常工作

并将其用作:

body {
  font-family: 'Josefin Sans', cursive;
}

12
投票

如果您正在使用Create React App环境,只需将@import规则添加到index.css:

@import url('https://fonts.googleapis.com/css?family=Anton');

在主React应用程序中导入index.css:

import './index.css'

React为您提供了内联样式,CSS模块或样式组件的选择,以便应用CSS:

font-family: 'Anton', sans-serif;

5
投票

在CSS文件中,例如create-react-app中的App.css,添加字体导入。例如:

@fontface {
  font-family: 'Bungee Inline', cursive;
  src: url('https://fonts.googleapis.com/css?family=Bungee+Inline')
}

然后只需将字体添加到同一css文件中的DOM元素即可。

body {
  font-family: 'Bungee Inline', cursive;
}

4
投票

你应该看看这个教程:https://scotch.io/@micwanyoike/how-to-add-fonts-to-a-react-project

import WebFont from 'webfontloader';

WebFont.load({
  google: {
    families: ['Titillium Web:300,400,700', 'sans-serif']
  }
});

我只是尝试了这种方法,我可以说它的效果非常好;)


3
投票

有同样的问题。结果我使用"而不是'

像这样使用@import url('within single quotes');

不是这样的@import url("within double quotes");


2
投票

我在我的css文件中添加了@import和@ font-face,并且它工作了.enter image description here


0
投票

这里所有好答案的另一个选择是npm包react-google-font-loader,找到了here

用法很简单:

import GoogleFontLoader from 'react-google-font-loader';

// Somewhere in your React tree:

<GoogleFontLoader
    fonts={[
        {
            font: 'Bungee Inline',
            weights: [400],
        },
    ]}
/>

然后你可以在CSS中使用姓氏:

body {
    font-family: 'Bungee Inline', cursive;
}

免责声明:我是react-google-font-loader包的作者。


-1
投票

它可能是最后链接的自动关闭标记,请尝试:

<link href="https://fonts.googleapis.com/css?family=Bungee+Inline" rel="stylesheet"/> 

并在您的main.css文件中尝试:

body,div {
  font-family: 'Bungee Inline', cursive;
}
© www.soinside.com 2019 - 2024. All rights reserved.