首页 > 解决方案 > 如何在 createMuiTheme() 中创建 css 类并直接使用它们,而无需从组件“类”道具中获取其值?

问题描述

我试图避免输入多余的代码。在多个组件中,我创建了相同的 css 类。我想使用 createMuiTheme() 将它们添加到主题中,然后只直接使用主题中的样式,而不必在 Component 道具上调用“类”道具。

我尝试在根组件上创建一个主题,如下所示:

const theme = createMuiTheme({
  palette:{
      primary: {
        main: '#47286E',
        light: '#D91677'
      },
      secondary: {
        main: '#9156D8' 
      },
  },

 fab: {
    position: "relative",
    top: 0,
    marginTop: 20px
    textTransform: 'none',
    width: 220,
    height: 50
  },

});

然后我将主题传递给其他组件使用

<MuiThemeProvider theme={theme}>

我尝试直接在组件内导入 fab 按钮

<Fab variant="extended" className={this.props.theme.fab} size='small'>
    Change
</Fab>

但是,当我尝试获得 fab css 类时,我似乎没有得到任何价值。我只是不想创造一个全新的

const styles = theme => {
    blabbla
}

如果我想要的主题已经在传递给其子组件的主题上,则使用“类”道具将其导入每个组件中。

标签: reactjsmaterial-ui

解决方案


我不认为createMuiTheme是为了那个。

或者,您可以只创建一个要重用的样式对象

const styles = {
  fab: {
    position: "relative",
    top: 0,
    marginTop: 20px
    textTransform: 'none',
    width: 220,
    height: 50
  }
};

只需在需要的地方导入并使用它

import fabStyles from '../../somewhere-everyone-can-get-it.js';
import styles from './styles-for-this-component.js';

...

withStyles({...fabStyles, ...styles})(Component);

如果您需要主题和样式。

withTheme(withStyles({...fabStyles, ...styles})(Component));

您也可以使用它recompose来清理它。


推荐阅读