Material UI:通过 SASS 变量更改主题颜色

Abi*_* A. 5 themes sass reactjs material-ui

我知道我们可以编辑Material UI的主题, 但我正在考虑让它变得动态,在我们可以设置 SASS 变量的地方,它会自动更新 Material UI 主题。

我使用 sass 来设计我的页面,这里是我使用的变量示例:

$primary-color: #1E79C7;
$secondary-color: #E5681A;
Run Code Online (Sandbox Code Playgroud)

目前对我来说,我对材质 ui 按钮执行以下操作,因为我希望我的设计尽可能多地放在一个地方

.app-button-blue {
  background-color: $primary-color !important; 
  margin: 5px;
}

.app-button-gray {
  background: transparent !important;
  box-shadow: none !important;
}

.app-button-white {
  background: transparent !important;
  box-shadow: none !important;
  border: $primary-color solid 1px !important;
}
Run Code Online (Sandbox Code Playgroud)

有没有办法让我使用这个 SASS 变量来覆盖材质 ui 的主题——比如设置主色和辅助色?

Kie*_*101 9

可以使用Webpack wizadry从 Sass/Scss 变量填充 MaterialUI 主题

调色板.scss

$primary: #1E79C7;
$secondary: #E5681A;

:export {
  primary: $primary;
  secondary: $secondary;
}
Run Code Online (Sandbox Code Playgroud)

主题.js

import { createMuiTheme } from '@material-ui/core/styles'
import palette from './palette.scss'

export const theme = createMuiTheme({
  palette: {
    primary: {
      main: palette.primary,
    },
    secondary: {
      main: palette.secondary,
    },
  }
})
Run Code Online (Sandbox Code Playgroud)

应用程序.js

import React from 'react'
import { ThemeProvider } from '@material-ui/core/styles'
import { theme } from './theme'

export const App = () => {
  return (
    <ThemeProvider theme={theme}>
       // App
    </ThemeProvider>
  )
}
Run Code Online (Sandbox Code Playgroud)

这意味着您可以使用 Sass 从同一个事实来源为非 Material UI 和 Material UI 组件设置样式和颜色

要设置其他组件的样式,只需使用 Sass 导入

@import './palette.scss'

.app-button-blue {
  background-color: $primary; // removed !important cos there's usually a better way
  margin: 5px;
}
Run Code Online (Sandbox Code Playgroud)


Luk*_*vey 6

Material UI 使用基于 javascript 的样式解决方案 (JSS),而不是像 SCSS 这样的 CSS 预处理器(请参阅样式解决方案)。

这意味着无法通过 SCSS 变量自定义 Material UI 主题。也不可能访问 CSS/SCSS 样式中的主题。

如果您想使用 SCSS 进行样式/主题化,您可以考虑使用Material Web 组件