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

如何在React Victory Chart(NextJS)中将字体修改为Poppins?

解决Victory Bar组件修改字体为Poppins的方法

步骤1:在NextJS中引入Poppins字体

NextJS推荐用next/font管理字体,避免性能问题:

  • 从next/font/google导入Poppins
  • 创建字体实例,按需指定需要的字重
  • 将字体应用到图表容器

步骤2:覆盖Victory组件的字体样式

Victory的字体样式可通过组件style属性或自定义主题覆盖,需处理坐标轴文本、tooltip文本等部分:

完整修改后的代码

import { VictoryBar, VictoryChart, VictoryTheme, VictoryTooltip } from "victory";
import { Poppins } from "next/font/google";

// 初始化Poppins字体,指定需要的字重
const poppins = Poppins({
  weight: ["400", "500"],
  subsets: ["latin"],
});

const data = [
  { reptile: "lizard", awesomeness: 3234 },
  { reptile: "snake", awesomeness: 2048 },
  { reptile: "crocodile", awesomeness: 2600 },
  { reptile: "alligator", awesomeness: 9000 },
];
const x = "reptile";
const y = "awesomeness";

function Victory() {
  return (
    <div className={poppins.className}>
      <VictoryChart 
        theme={VictoryTheme.material} 
        domainPadding={{ x: 20 }}
        // 覆盖坐标轴标签和刻度的字体
        style={{
          axisLabel: { fontFamily: poppins.style.fontFamily },
          tickLabels: { fontFamily: poppins.style.fontFamily },
        }}
      >
        <VictoryBar
          style={{ data: { fill: "#2563eb" } }}
          data={data}
          x={x}
          y={y}
          alignment="start"
          labels={({ datum }) => datum.awesomeness}
          // 自定义Tooltip的字体
          labelComponent={
            <VictoryTooltip 
              style={{
                label: { fontFamily: poppins.style.fontFamily },
              }}
            />
          }
        />
      </VictoryChart>
    </div>
  );
}

export default Victory;

可选:自定义全局主题(多图表统一字体)

如果项目中有多个Victory图表,可自定义主题全局设置字体,避免重复代码:

import { createTheme } from "victory";

const customTheme = createTheme(VictoryTheme.material, {
  typography: {
    fontFamily: poppins.style.fontFamily,
  },
});

// 在VictoryChart中使用自定义主题:
<VictoryChart theme={customTheme} ... />

补充说明

  • next/font导入的字体是本地托管,不依赖外部CDN,性能更优
  • 若不想用next/font,也可通过CSS全局导入Poppins,再在style中指定fontFamily: 'Poppins, sans-serif'
  • 需确保覆盖所有需要修改字体的区域:坐标轴标签、刻度文本、tooltip内容

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 11:37:51