React 中的字型
我們將介紹如何在 react 中安裝字型和使用字型。
React 中的字型
字型是網站最重要的部分。在 React 應用程式中安裝字型有不同的方法。
最常見的方法是匯入字型。我們可以在命令提示符下使用 npm 或 yarn 匯入字型。讓我們以安裝 Quicksand 為例。
# react CLI
yarn add typeface-quicksand
或者
# react
npm install typeface-quicksand --save
安裝後,我們需要將它匯入到 index.tsx 檔案中。
# react
import 'typeface-quicksand';
現在,我們可以在 style.css 檔案中使用它。
# react
h1,
p {
font-family: Quicksand;
}
輸出:

在 react 中安裝字型的另一種方法是直接在 index.html 或 style.css 檔案中新增連結。讓我們以安裝 Lato 字型為例。
# react
<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=Lato&display=swap" rel="stylesheet">
或者,
# react
<style>
@import url('https://fonts.googleapis.com/css2?family=Lato&display=swap');
</style>
讓我們匯入 Lato 字型並更改標題和段落的樣式。
# react
@import url('https://fonts.googleapis.com/css2?family=Lato&display=swap');
h1,
p {
font-family: Lato;
}
輸出:

在 react 中安裝字型的另一種方法是下載並新增到我們的原始碼中。
我們可以輕鬆地從 fonts.google.com 下載字型並將它們移動到 src 目錄中的 fonts 目錄。
現在,在 style.css 中,使用 @font-face 新增字型。
# react
@font-face {
font-family: 'Lato';
src: local('Lato'), url(./fonts/Lato-Regular.otf) format('opentype');
}
對於 ttf 格式,我們必須提到 format('truetype'),對於 woff 格式,我們必須提到 format('woff')。
現在,我們可以輕鬆地使用這種字型進行樣式設定。
# react
h1,
p {
font-family: Lato;
}
輸出:

另一種方法是使用 web-font-loader 包。我們可以使用 npm 或 yarn 輕鬆安裝 web-font-loader 包。
# react
yarn add webfontloader
或者,
# react
npm install webfontloader --save
現在,在 index.tsx 中,我們可以匯入並指定我們需要的字型。
# react
import WebFont from 'webfontloader';
WebFont.load({
google: {
families: ['Lato:300,400,700', 'sans-serif']
}
});
所以現在,我們學習了四種在 React 中安裝和使用字型的不同方法。
Rana is a computer science graduate passionate about helping people to build and diagnose scalable web application problems and problems developers face across the full-stack.
LinkedIn