首页 > 解决方案 > 在深色/浅色样式覆盖之间切换

问题描述

我想覆盖一些基于theme.type原生的图标的颜色PaletteColor。我可以type像这样检查并有条件地设置颜色:

const useStyles = makeStyles((theme: Theme) =>
  createStyles({
    someIcon: {
      color:
        theme.palette.type === "dark"
          ? theme.palette.warning.dark
          : theme.palette.warning.light,
    },
  })
);

每次我想覆盖某些东西时,这都非常冗长,因此可以将其重构为themeColor以下内容:

const themeColor = (theme: Theme, color: PaletteColor) =>
  theme.palette.type === "dark"
    ? color.dark
    : color.light;

const useStyles = makeStyles((theme: Theme) =>
  createStyles({
    someIcon: {
      color: themeColor(theme, theme.palette.warning)
    },
  })
);

现在让我想,Material-UI 是否有一些已经这样做的本机助手?

标签: material-ui

解决方案


我在 Material-UI 源代码中挖掘了一段时间,这是我发现的:

  • 您可以在此处查看与 Material-UI 样式相关的任何潜在辅助方法。

  • 这个提交更改palette.typepalette.mode,如果您 Ctrl+F 搜索'light' ?or 'dark' ?,您会看到他们还使用三元运算符根据dark|分配颜色 light模式,所以我怀疑他们是否有任何辅助方法,例如您在第二个片段中描述的方法。


推荐阅读