You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Next.UI与React.js中配置及使用自定义字体的技术问询

NextUI 自定义字体配置完整示例

一、字体导入方法

NextUI支持两种字体来源:系统预装字体、自定义Web/本地字体,具体实现如下:

1. 本地字体导入

假设字体文件放在src/fonts目录下(如Roboto-Regular.ttf、Roboto-Bold.ttf):

  • 在全局样式文件(比如src/index.css)中声明字体:
@font-face {
  font-family: 'Roboto';
  src: url('./fonts/Roboto-Regular.ttf') format('truetype');
  font-weight: 400;
  font-style: normal;
  font-display: swap;
}

@font-face {
  font-family: 'Roboto';
  src: url('./fonts/Roboto-Bold.ttf') format('truetype');
  font-weight: 700;
  font-style: normal;
  font-display: swap;
}
  • 在index.js中引入该全局样式:
import './index.css';

2. Web字体导入(以Google Fonts为例)

直接在public/index.html的<head>标签中添加字体链接:

<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=Roboto:wght@400;700&display=swap" rel="stylesheet">

二、NextUI 主题配置

在index.js中修改fonts配置项,将自定义字体映射到NextUI的字体分组:

import { createTheme, NextUIProvider } from '@nextui-org/react';
import ReactDOM from 'react-dom/client';
import './index.css'; // 本地字体需引入全局样式
import App from './App';

const theme = createTheme({
  type: "light",
  theme: {
    colors: {}, // 你的颜色配置
    fonts: {
      sans: 'Roboto, sans-serif', // 自定义无衬线字体, fallback到系统默认无衬线
      mono: 'JetBrains Mono, monospace', // 自定义等宽字体
      serif: 'Georgia, serif', // 自定义衬线字体
    },
  }
});

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <NextUIProvider theme={theme}>
    <App />
  </NextUIProvider>
);

三、字体使用方式

1. 全局自动生效

配置完成后,NextUI的内置组件(按钮、文本、输入框等)会自动使用你定义的对应字体分组(默认用sans字体)。

2. 局部自定义

如果需要在特定元素中指定字体,可通过以下两种方式实现:

  • 使用NextUI的styled工具:
import { styled } from '@nextui-org/react';

const CustomSerifText = styled('p', {
  fontFamily: '$serif', // 直接引用主题中定义的serif字体组
  fontSize: '1.2rem',
});

// 组件使用
<CustomSerifText>这是衬线字体显示的文本</CustomSerifText>
  • 行内样式:
<p style={{ fontFamily: theme.theme.fonts.mono }}>这是等宽字体文本</p>

四、支持的字体类型

NextUI对字体格式无特殊限制,只要浏览器支持即可:

  • 本地字体:支持TTF、OTF、WOFF、WOFF2、EOT等格式
  • Web字体:主流CDN提供的字体(如Google Fonts、Adobe Fonts)均可直接使用

内容的提问来源于stack exchange,提问作者Takkie253

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 16:05:20