材质用户界面:通过SASS变量更改主题颜色

时间:2018-09-30 07:56:44

标签: sass themes material-ui

我知道我们可以编辑材质UI(https://material-ui.com/customization/themes/)的主题,但是我一直在考虑使其动态化,在其中可以设置SASS变量,它将自动更新材质UI主题。

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

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

目前对我来说,我对材质的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;
}

我是否可以使用此SASS变量来覆盖材质ui的主题-例如设置原色和副色?

4 个答案:

答案 0 :(得分:0)

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

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

如果要使用SCSS进行样式/主题设置,则可以考虑使用Material Web Components

答案 1 :(得分:0)

这可能并不是您想要实现的,但是下面的文章介绍了如何导出SASS变量。 https://til.hashrocket.com/posts/sxbrscjuqu-share-scss-variables-with-javascript 然后,您可以将它们导入JS并使用它们来设置主题。

答案 2 :(得分:0)

示例on this GitHub issue提出了实现方法。

import React from 'react';
import { withStyles } from '@material-ui/core';

const cssVariables = (theme) => ({
  '@global': {
    ':root': {
      '--color-primary': theme.palette.primary.main,
      '--color-secondary': theme.palette.secondary.main,
    }
  }
});

const RootComponent = () => {
  return <div>Whatever...</div>
}

export default withStyles(cssVariables, RootComponent);

请注意,RootComponentThemeProvider内部进行初始化。

答案 3 :(得分:0)

可以使用 Webpack wizadry

从 Sass/Scss 变量填充 MaterialUI 主题

调色板.scss

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

:export {
  primary: $primary;
  secondary: $secondary;
}

theme.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,
    },
  }
})

App.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>
  )
}

这意味着您可以使用 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;
}