reactjs - 如何在 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
}
如果我想要的主题已经在传递给其子组件的主题上,则使用“类”道具将其导入每个组件中。
解决方案
我不认为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
来清理它。
推荐阅读
- c# - 为什么在 WPF 数据网格中设置选择不起作用?
- matlab - 如何使用matlab从firebase上传/下载文件?
- java - 从java中的不同类写入同一个文件
- javascript - 如何将日期格式转换为“2019-04-24T04:27:14.867Z”
- node.js - Sailsjs 蓝图未捕获“beforeCreate”或“beforeUpdate”模型函数生成的错误
- jquery - 正则表达式从 url 字符串中获取价格范围数字
- matlab - 熔化样品的边缘检测和跟踪
- php - 如何加入2个表并返回值
- google-chrome - 如何使用 chrome.printerProvider
- python - 根据条件从数组中选择值