如何在ReactJS中使用Google字体
在本文中,我们将学习如何在ReactJS中使用Google字体。Google字体是一个广受欢迎的开源Web字体库,提供了丰富的字体样式,可以提升Web应用的视觉吸引力。在ReactJS项目中集成Google字体可以使用多种方法。
以下是在React.js中添加Google字体的一些常见方法:
- 手动添加Google字体。
- 使用styled-components库。
在React JS应用程序中添加Google字体非常简单,我们将详细介绍使用它们的完整步骤。
创建React应用程序和安装模块的步骤
步骤1: 使用以下命令创建一个React应用程序:
npm create-react-app appname
步骤2: 在创建项目文件夹即文件夹名称之后,使用以下命令进入该文件夹:
cd foldername
项目结构
方法1:手动添加谷歌字体
在ReactJS中手动添加谷歌字体,方法是在public/index.html文件的<head>
部分中包含谷歌字体的链接标签,然后在React组件中使用CSS应用字体。
步骤1:从谷歌字体网站上选择一个字体。
访问链接-浏览字体–谷歌字体,然后选择要添加的字体。这里我们以Montserrat字体为例。
步骤2:将字体集成到React中
复制字体的<link>
标签到React应用的public/index.html文件中以在项目中使用:
<link rel=”preconnect” href=”https://fonts.googleapis.com”>
<link rel=”preconnect” href=”https://fonts.gstatic.com” crossorigin>
<link href=”https://fonts.googleapis.com/css2?family=Montserrat:wght@500&display=swap” rel=”stylesheet”>
步骤3:使用导入的字体
body {
font-family: 'Montserrat', sans-serif;
}
示例1: 下面的示例演示了在特定的React元素中使用Google字体。
App.js
import "./styles.css";
export default function App() {
return (
<div className="App">
<h1 className="gfg">GeeksforGeeks</h1>
<h2>How to use Google fonts in React JS</h2>
<div className="font-container">
<p className="text">
This text is written in Monsterrat Font
from Google Fonts{" "}
</p>
</div>
</div>
);
};
index.css
.App {
text-align: center;
}
.gfg {
color: green;
}
.font-container {
font-family: "Montserrat", sans-serif;
}
.text {
font-size: 30px;
};
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport"
content="width=device-width, initial-scale=1" />
<link rel="preconnect"
href="https://fonts.googleapis.com">
<link rel="preconnect"
href="https://fonts.gstatic.com" crossorigin>
<link href=
"https://fonts.googleapis.com/css2?family=Montserrat:wght@500&display=swap"
rel="stylesheet">
<title>React App</title>
</head>
<body>
<div id="root"></div>
</body>
</html>
运行步骤:
npm start
输出:
方法2:使用styled-components库
在ReactJS中使用styled-components库,通过定义组件样式并使用字体导入语法来指定所需的font-family属性,以应用Google字体。
步骤1:安装库
npm install styled-components
步骤2:使用Google 字体
import styled from 'styled-components';
const StyledText = styled.p`
font-family: 'FontStyle', sans-serif;
`;
function App() {
return (
<div>
<StyledText>
This text uses Google Fonts.
</StyledText>
</div>
);
};
示例2: 下面的示例演示了在React应用程序中使用styled-components库的用法。
App.js
import "./styles.css";
import React from 'react';
import styled from 'styled-components';
const StyledText = styled.h1`
font-family: 'Monsterrat', sans-serif;
font-size: 30px;
`;
export default function App() {
return (
<div className="App">
<h1 className="gfg">
GeeksforGeeks
</h1>
<h2>
How to use Google fonts in React JS
</h2>
<div>
<StyledText >
Welcome to GeeksforGeeks!
</StyledText>
</div>
</div>
);
};
index.css
.App {
text-align: center;
}
.gfg {
color: green;
}
.text {
font-size: 30px;
}
运行步骤:
npm start
输出: