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

如何为MUI X Gauge组件中的两组文本设置不同样式

解决MUI X Gauge组件文本分段样式问题

你可以直接在text回调中返回JSX元素(而非纯字符串),Gauge组件的text属性支持接收ReactNode类型,这样就能为不同文本片段设置独立样式:

方案1:使用内联样式的span

import { Gauge, gaugeClasses } from '@mui/x-charts/Gauge';

const currCal = 10;
const percentageCal = 10;

return (
  <div>
    <Gauge
      value={percentageCal}
      width={250}
      height={250}
      startAngle={0}
      endAngle={360}
      innerRadius="95%"
      outerRadius="100%"
      valueMin={0}
      sx={{
        [`& .${gaugeClasses.valueText}`]: {
          transform: "translate(0px, 0px)",
          lineHeight: 1.2,
          textAlign: 'center',
        },
      }}
      text={() => (
        <div>
          <span style={{ fontSize: 30, display: 'block' }}>{currCal}</span>
          <span style={{ fontSize: 20 }}>calories</span>
        </div>
      )}
    />
  </div>
);

方案2:使用MUI Typography组件

如果你偏好使用MUI的Typography组件统一样式体系,同样可以嵌套实现:

import { Gauge, gaugeClasses } from '@mui/x-charts/Gauge';
import { Typography } from '@mui/material';

const currCal = 10;
const percentageCal = 10;

return (
  <div>
    <Gauge
      value={percentageCal}
      width={250}
      height={250}
      startAngle={0}
      endAngle={360}
      innerRadius="95%"
      outerRadius="100%"
      valueMin={0}
      sx={{
        [`& .${gaugeClasses.valueText}`]: {
          transform: "translate(0px, 0px)",
          textAlign: 'center',
        },
      }}
      text={() => (
        <div>
          <Typography variant="h4" component="span" display="block">
            {currCal}
          </Typography>
          <Typography variant="body1" component="span">
            calories
          </Typography>
        </div>
      )}
    />
  </div>
);

关键说明

  • 移除valueText类中的全局fontSize设置,避免覆盖内部自定义文本样式;
  • 通过display: 'block'让数值和单位分行显示,配合lineHeight保证排版美观;
  • Gauge的text属性并非仅支持字符串,官方定义其类型为ReactNode,因此可自由返回JSX结构。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 04:06:10