Material ui中的CSS变量-createMuiTheme

问题描述

我正在尝试使用定义为css变量my-pallette.scss的现有颜色来创建材质ui主题

:root {
  --primary-color: '#FF0000';
  ...
}

并像这样使用它:

import { createMuiTheme } from '@material-ui/core/styles';

export const muiTheme = createMuiTheme({
  palette: {
    primary: {
      main: 'var(--primary-color)',},});

这会引发错误

未捕获的错误:Material-UI:不支持var(--primary-color)颜色。 我们支持以下格式:#nnn,#nnnnnn,rgb(),rgba(),hsl(),hsla()。

根据这个Github线程:Support CSS variables as theme option,目前不支持

有没有解决方法,所以我可以在材料ui var(--primary-color)中将createMuiTheme用作原色颜色?

最终目标是以最简单的形式使用材料ui组件,并用我的颜色覆盖其原色,基础颜色等颜色。

<Radio color="primary" />

我已经尝试过使用托盘中的颜色,如下所示:

const cssVariables = {
  primaryColor: getComputedStyle(document.documentElement).getPropertyValue('var(--primary-color)'),};

并使用cssVariables.primaryColor,但这不起作用,并且感觉很违反直觉。

我最后的解决方案是将调色板作为常规对象复制,并按原样使用它,但这似乎是维护的噩梦。

解决方法

这种丑陋的解决方法可行,但是我怀疑您可能尚未初始化样式表时在模块作用域中调用getComputedStyle()

尝试将其放在这样的render方法中。

const [theme,setTheme] = React.useState(null);

React.useLayoutEffect(() => {
  const color = getComputedStyle(document.documentElement)
    .getPropertyValue("--your-css-color")
    .trim(); // the result have a leading whitespace.

  setTheme(
    createMuiTheme({
      palette: {
        primary: {
          main: color
        }
      }
    })
  );
},[]);

实时演示

Edit Material-UI TextField Underline Override (forked)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...