ReactJS - 添加谷歌字体库实例

1,122 阅读3分钟

在这篇文章中,How to integrate google fonts library in Reactjs application with examples 。这涵盖了将google字体lato集成到reactjs项目中的*多种方法

create-react-app 命令创建具有所有文件和构建管道的新应用程序。它提供了所有最新的reactjs及其依赖项。

npx create-react-app react-google-fonts
Success! Created react-google-fonts at B:\blog\jswork\react-google-fonts
Inside that directory, you can run several commands:

  yarn start
    Starts the development server.

  yarn build
    Bundles the app into static files for production.

  yarn test
    Starts the test runner.

  yarn eject
    Removes this tool and copies build dependencies, configuration files
    and scripts into the app directory. If you do this, you can’t go back!

We suggest that you begin by typing:

  cd react-google-fonts
  yarn start

Happy hacking!

这将创建一个反应式应用程序react-google-fonts ,包括所有需要的文件和项目结构,安装依赖项以开始运行。

进入应用程序根目录,使用以下方式启动服务器npm start

cd react-google-fonts
npm start
react-google-fonts@0.1.0 start B:\blog\jswork\react-google-fonts
react-scripts start
Compiled successfully!

You can now view react-google-fonts in the browser.

  Local:            http://localhost:3002

React应用程序在localhost:3002下运行。

进入google library链接,选择你想集成到react应用程序的字体。Lato字体被选中,并给出以下网址

https://fonts.googleapis.com/css2?family=Lato:wght@300&display=swap

以下是在应用程序中添加google字体库的方法,无需托管。

@import google字体

@import css用来导入外部css库到当前的样式中。它可以在全局样式(app.css)或特定组件样式表中使用。转到src文件夹中的App.css 。添加以下条目以在React应用程序中启用Lado字体

@import url('https://fonts.googleapis.com/css2?family=Lato:wght@300&display=swap');
html,body{
font-family: 'Lato', sans-serif;
}

链接谷歌字体

另一种方法是在public/index.html的head部分添加link 标签。

<html>
<head>
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Lato:wght@300&display=swap" rel="stylesheet">
</head>
<body></body>
</html>

完整的React组件代码

import "./App.css";

function App() {
  return (
    
      React Google fonts library integration example
      This is testing google fonts LATO in React application
    
  );
}
export default App;

CSS样式包含在html和body中配置的font-family: Lato, sans-serif; 的规则

html,
body {
  font-family: "Lato", sans-serif;
}
App {
  font-size: 24px;
}

p {
  font-size: 14px;
}

而你在浏览器中看到的输出是Add google font library in react application

用font-face声明托管字体

在这种方法中,css字体库被复制到react应用程序中。你将看到如何将google字体添加到react应用的样式表中:

  • 转到(google字体Lato)[fonts.google.com/specimen/La…]
  • 点击Download family ,它将在本地下载Lato字体家族的压缩文件。
  • 解压缩文件并复制到src/fonts

你可以看到项目文件夹结构和字体文件夹文件。Add google font library in react application

在react项目的index.css文件中,添加Lato font-face声明,在React应用程序中启用谷歌字体。

@font-face {
      font-family: 'Lato';
      src: local('Lato'), url('./fonts/roboto.ttf')  format('truetype'), 
    }

css属性配置如下

heading{
  font-family: "Lato", sans-serif;
}

总结

在本教程中,你学到了在Reactjs应用程序中整合谷歌字体库的不同方法

  • @import css功能
  • 链接属性
  • 使用@font-face声明托管css文件

重要的是,第一种和第二种方法是在Reactjs应用程序中添加google字体库的简单方法,但由于它指向外部依赖,所以性能并不理想。

最后,托管css文件在性能、依赖性和可维护性方面都不错。