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

如何在MUI React 5中定义引用调色板的Typography caption变体?

在Material UI 5中为Typography的caption变体默认设置text.secondary颜色

可以通过在Typography变体配置中使用回调函数引用主题调色板来实现需求,具体步骤如下:

1. 调整Typography变体的配置

将caption变体的color属性改为函数形式,接收theme参数并返回调色板中的text.secondary值:

import { TypographyOptions, Theme } from '@mui/material/styles';

export const typography: TypographyOptions = {
  caption: {
    fontSize: '0.875rem',
    // 用函数获取主题中的颜色值
    color: (theme: Theme) => theme.palette.text.secondary,
  },
};

2. 更新类型声明

因为现在color支持字符串或函数,需要修改自定义的Text接口,兼容函数类型:

import { Theme } from '@mui/material/styles';

export interface Text {
  fontSize: string;
  // 允许color为字符串或返回字符串的主题回调函数
  color: string | ((theme: Theme) => string);
}

declare module '@mui/material/styles' {
  interface TypographyVariants {
    caption: Text;
  }

  interface TypographyVariantsOptions {
    caption: Text;
  }
}

3. 使用方式

配置完成后,直接使用variant="caption"就会自动应用text.secondary颜色,无需额外指定color属性:

<Typography variant="caption">
  自动应用text.secondary颜色的文本
</Typography>

原理说明:Material UI 5的主题配置中,Typography变体的属性支持接收回调函数,函数会传入当前主题对象,这样就能直接引用主题调色板中的变量,而不局限于静态CSS颜色值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 00:00:08