如何在React的.tsx文件中仅用styled-components导入使用Google Fonts
在TSX中用Styled Components引入Inter字体(无需CSS文件)
下面提供两种完全在TSX文件内实现的可行方案,无需依赖单独CSS文件:
方案1:通过createGlobalStyle定义@font-face
直接在TSX中用全局样式组件引入Inter字体的@font-face规则:
- 创建全局字体样式组件(比如
GlobalFonts.tsx):
import { createGlobalStyle } from 'styled-components'; const GlobalFonts = createGlobalStyle` @font-face { font-family: 'Inter'; font-style: normal; font-weight: 400; font-display: swap; src: url(https://fonts.gstatic.com/s/inter/v12/UcC73FwrK3iLTeHuS_fvQtMwCp50KnMa1ZL7W0Q5nw.woff2) format('woff2'); unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; } @font-face { font-family: 'Inter'; font-style: normal; font-weight: 500; font-display: swap; src: url(https://fonts.gstatic.com/s/inter/v12/UcC73FwrK3iLTeHuS_fvQtMwCp50KnMa1ZL7W0Q5nw.woff2) format('woff2'); unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; } /* 按需添加700、800等其他字重,链接可从Google Fonts官网提取 */ `; export default GlobalFonts;
- 在根组件(比如
App.tsx)中引入这个全局样式:
import GlobalFonts from './GlobalFonts'; import { StyledHeader, StyledContainer } from './your-styled-components'; function App() { return ( <> <GlobalFonts /> <StyledHeader>Hello Inter Font</StyledHeader> <StyledContainer> {/* 页面内容 */} </StyledContainer> </> ); } export default App;
- 在你的styled-components中直接使用Inter字体:
import styled from 'styled-components'; export const StyledHeader = styled.h1` font-family: 'Inter', sans-serif; font-weight: 500; `; export const StyledContainer = styled.div` font-family: 'Inter', sans-serif; font-weight: 400; `;
方案2:用webfontloader动态加载
这种方式无需手动编写@font-face,通过第三方包自动加载Google Fonts:
- 先安装依赖:
npm install webfontloader # 或 yarn add webfontloader
- 在根组件中初始化字体加载:
import WebFont from 'webfontloader'; import { useEffect } from 'react'; import { StyledHeader } from './your-styled-components'; function App() { useEffect(() => { WebFont.load({ google: { families: ['Inter:400,500,700'], // 按需指定需要的字重 }, }); }, []); return ( <StyledHeader>Hello Inter</StyledHeader> ); } export default App;
- 同样在styled-components中直接引用字体:
import styled from 'styled-components'; export const StyledText = styled.p` font-family: 'Inter', sans-serif; font-weight: 700; `;
注意事项
- 方案1无需额外依赖,字体加载逻辑更直接;方案2适合需要动态控制加载时机或逻辑的场景;
- 字体链接可从Google Fonts官网获取:打开Inter字体页面,选择需要的字重后,查看页面提供的CSS代码,提取对应字重的
src链接即可。
内容的提问来源于stack exchange,提问作者Rohit Tagadiya
相关产品推荐
相关产品推荐

