从MUI调色板颜色名称获取颜色代码

问题描述 投票:0回答:1

我想知道是否有某种方法可以从 Material UI 中的调色板颜色名称获取十六进制代码或任何颜色代码?

我的用例如下:

我有一个样式徽章,我希望能够像具有颜色属性的普通徽章一样进行自定义。所以我的组件看起来像这样:

import { styled, alpha } from "@mui/material/styles";
import Badge, { BadgeProps } from "@mui/material/Badge";

const PulsingBadge = styled(Badge)<BadgeProps>(({ theme, color }) => ({
  position: "relative",
  "&:before": {
    content: '""',
    position: "absolute",
    top: "50%",
    left: "50%",
    transform: "translate(-50%, -50%)",
    width: "5px",
    height: "5px",
    borderRadius: "50%",
    background: color,
    opacity: 0.7,
    animation: `pulsing 1500ms ${theme.transitions.easing.easeOut} infinite`,
  },
  "@keyframes pulsing": {
    "0%": {
      width: "5px",
      height: "5px",
      opacity: 0.7,
    },
    "70%": {
      width: "24px",
      height: "24px",
      opacity: 0.05,
    },
    "100%": {
      width: "26px",
      height: "26px",
      opacity: 0.0,
    },
  },
}));

export default PulsingBadge;

这句话特别重要:

background: color,

但这会导致编译

background: warning
,这显然不被识别为颜色。另外,如果我尝试使用像
alpha(color, 0.5)
这样的方法,我也会收到以下错误:

MUI:不支持

warning
颜色。支持以下格式: #nnn、#nnnnnn、rgb()、rgba()、hsl()、hsla()、颜色()。

我想知道调色板中是否有像

theme.palette.get(color)
这样的吸气剂。我尝试了
theme.palette[color]
但由于显然颜色属性可能是未定义的,我收到以下错误:

类型“未定义”不能用作索引

这是一个 codesandbox ,其中包含一个可重现性最低的示例!

我觉得我错过了一些东西,因为这感觉像是一个非常基本的功能,可能包含在 MUI 中,但我似乎无法在任何地方找到解决方案...

感谢您的帮助!

reactjs typescript material-ui
1个回答
0
投票

您可以从样式组件中的

theme
对象获取颜色。

参见分叉示例此处

© www.soinside.com 2019 - 2024. All rights reserved.