我想在我的 React 应用程序中有效地使用 Google Fonts。
我尝试将Google Fonts导入到index.css文件中,但我想知道是否有更好的方法。
更具体地说,我只想将 Google Fonts 导入到 React 组件中,并在同一个文件中使用它。
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;
现在,字体将直接在 Component 范围内使用,无需外部 CSS 文件。