material-ui 公开了许多用于样式的组件。有两种方法可以做到这一点。
全局应用样式
您可以全局设置组件的样式并将其应用于主题。这方面的一个例子是这样的(复制自文档http://www.material-ui.com/#/customization/themes):
import React from 'react';
import {cyan500} from 'material-ui/styles/colors';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import AppBar from 'material-ui/AppBar';
// This replaces the textColor value on the palette
// and then update the keys for each component that depends on it.
// More on Colors: http://www.material-ui.com/#/customization/colors
const muiTheme = getMuiTheme({
palette: {
textColor: cyan500,
},
appBar: {
height: 50,
},
});
class Main extends React.Component {
render() {
// MuiThemeProvider takes the theme as a property and passed it down the hierarchy
// using React's context feature.
return (
<MuiThemeProvider muiTheme={muiTheme}>
<AppBar title="My AppBar" />
</MuiThemeProvider>
);
}
}
export default Main;
正如您在此处看到的,appBar 组件的高度为 50 像素,这意味着每次您在应用 muiTheme 的树的下方将 appbar 组件添加到应用程序时,它的高度都会为 50 像素。这是您可以为每个组件应用的所有样式的列表https://github.com/callemall/material-ui/blob/master/src/styles/getMuiTheme.js。
使用样式属性应用样式
要将样式应用于单个组件,通常可以使用 style 属性并将所需样式传递给它。
这是文档中的另一个示例,其中 12px 的边距应用于 RaisedButton。
import React from 'react';
import RaisedButton from 'material-ui/RaisedButton';
const style = {
margin: 12,
};
const RaisedButtonExampleSimple = () => (
<div>
<RaisedButton label="Default" style={style} />
<RaisedButton label="Primary" primary={true} style={style} />
<RaisedButton label="Secondary" secondary={true} style={style} />
<RaisedButton label="Disabled" disabled={true} style={style} />
<br />
<br />
<RaisedButton label="Full width" fullWidth={true} />
</div>
);
export default RaisedButtonExampleSimple;
现在,样式在同一个文件中定义,但您可以在单独的文件中定义它们并将它们导入到您使用组件的文件中。
如果您想应用多种样式,则可以使用展开运算符,如下所示:style={{...style1,...style2}}。
通常,您使用 style 属性为组件(根元素)中的特定事物设置样式,但某些组件具有多个属性来设置组件的不同元素的样式。在本页http://www.material-ui.com/#/components/raised-button的属性下,可以看到有style属性,labelStyle和rippleStyle来设置RaisedButton不同部分的样式。
检查您正在使用的组件下的属性,看看您可以使用哪个样式属性,否则请检查您可以覆盖的可用全局样式属性。希望这会有所帮助!