问题描述
我正在尝试使用定义为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
}
}
})
);
},[]);