在 React 应用程序中使用 Google Fonts 的最佳方式是什么?

问题描述 投票:0回答:1

我想在我的 React 应用程序中有效地使用 Google Fonts。

我尝试将Google Fonts导入到index.css文件中,但我想知道是否有更好的方法。

更具体地说,我只想将 Google Fonts 导入到 React 组件中,并在同一个文件中使用它。

css reactjs fonts
1个回答
0
投票
import React, { useEffect } from 'react';

const Component = () => {
  useEffect(() => {
    const link = document.createElement('link');
    link.href = ''; // add your fonts link here
    link.rel = 'stylesheet';
    document.head.appendChild(link);

    return () => {
      document.head.removeChild(link);
    };
  }, []);

  return (
    <div>
      <p style={{ fontFamily: 'Roboto, sans-serif' }}>you can use fonts here</p>
    </div>
  );
};

export default Component;
  1. 我们使用 useEffect 钩子动态添加一个元素到 组件安装时文档的头部。这个元素 从 Google Fonts 导入字体样式。
  2. 我们返回清理 useEffect 挂钩中的函数可在组件卸载时删除动态添加的元素,从而防止内存泄漏。

现在,字体将直接在 Component 范围内使用,无需外部 CSS 文件。

© www.soinside.com 2019 - 2024. All rights reserved.