您可以通过updating the theme 更改背景和其他颜色。这样您就可以自定义主要/次要背景和文本颜色,以及在您的样式中使用它们。
至于特定组件的自定义样式;这个想法是使用withStyles 作为高阶组件,包装你的组件。它以theme 为参数,并将classes 作为道具传递给包装的组件。
例子:
import { withStyles } from '@material-ui/core/styles/withStyles';
const styles = theme => ({
someClass: {
padding: theme.spacing.unit * 5
},
otherClass: {
background: 'red'
}
});
定义样式后,您可以在组件中使用它们,如下所示:
const MyComponent = (props) => {
return (<Button className={props.classes.someClass}>Some Action</Button>)
}
export default withStyles(styles)(MyComponent);
withStyles 会将 props 中的styles 传递为classes,然后您就可以使用它们了。如果你使用功能组件,你可以通过props.classes访问它们,如果你扩展Component,它们将在this.props.classes中
如果你想使用多个类,你需要安装 classnames 依赖,并导入它:
import React from 'react';
import { withStyles } from '@material-ui/core/styles/withStyles';
import classNames from 'classnames';
const styles = theme => ({
someClass: {
padding: theme.spacing.unit * 5
},
otherClass: {
background: 'red'
}
});
const MyComponent = (props) => {
return (<Button className={classNames(props.classes.someClass, props.classes.otherClass)}>Some Action</Button>)
}
export default withStyles(styles)(MyComponent);
classes 属性也可用于设置多个类,但这取决于 Material-UI 组件样式 API。比如对于Tab组件
<Tab label="Hello" classes={ { root: classes.tab, selected: classes.tabSelected }} />
默认采用root作为样式,选择tab时会应用selected。在这种情况下,styles 将包含:
const styles = theme => ({
tab: {
minWidth: 'auto',
fontSize: '11px',
fontWeight: 'bold'
},
tabSelected: {
background: theme.palette.background.paper,
color: theme.palette.secondary.main
},
};
请注意,这些使用 Tab 的 CSS API,将自定义样式映射到预定义的类名。
当然,带有Tab 的组件需要包装在withStyles(styles)(Component) 中。
这是一个live example,带有自定义主题,以及包含多个类的自定义按钮。