我如何在材料-ui中实现自定义主题呢? 我阅读了文档,但我真的不了解它
答案 0 :(得分:3)
这很简单,这是一个例子
// First we need the theme provider and the theme creator
import {createMuiTheme, MuiThemeProvider} from 'material-ui/styles';
// For this example I'll also be using the amber and blue color profiles
import amber from 'material-ui/colors/amber';
import blue from 'material-ui/colors/blue';
// Now let us create our theme
const theme = createMuiTheme({
palette: {
type: 'dark',
primary: amber,
secondary: {
...blue // I'm using the spread operator because I want to overwrite some colors
A400: '#A7FFEB' // Overwrite the accent 400 color with custom
}
}
});
// Let my components know about the theme
ReactDOM.render(
<MuiThemeProvider theme={theme}>
<App/>
</MuiThemeProvider>
)
这很简单,但它得到了重点。 material-ui提供的颜色配置文件是这样的对象:
{
50: string;
100: string;
200: string;
300: string;
400: string;
500: string;
600: string;
700: string;
800: string;
900: string;
A100: string;
A200: string;
A400: string;
A700: string;
contrastDefaultColor: 'light' | 'dark';
}
因此,如果你想制作自己的,你可以通过创建一个跟随上面接口的对象。主题提供程序接受主要调色板,辅助调色板和错误调色板。它根据您配置组件的方式在内部决定使用该调色板的颜色。
您可以设置大量其他选项,完整文档为here
这是我开发的自定义脚本,用于帮助构建自定义主题(如果它有用)
import tinycolor from 'tinycolor2'
function buildPaletteFrom(color, accent) {
accent = accent || color;
color = tinycolor(color).darken(25);
let i = 1;
let palette = {};
while (i < 10) {
color = color.lighten(5);
palette[(10 - i) * 100] = color.toHexString();
i++;
}
palette['50'] = tinycolor(palette['100']).lighten(5);
palette['contrastDefaultColor'] = tinycolor(palette['500']).isLight() ? dark : light;
palette['A100'] = tinycolor(accent).lighten(20).saturate().brighten().toHexString();
palette['A200'] = tinycolor(accent).lighten(15).saturate().brighten().toHexString();
palette['A400'] = tinycolor(accent).toHexString();
palette['A700'] = tinycolor(accent).darken(10).saturate().brighten().toHexString();
if (palette['A400'] === palette['500']) {
palette['A400'] = tinycolor(palette['500']).lighten(5).saturate().brighten().toHexString();
}
return palette
}
您可以像这样使用
const primary = '#56B9D0';
const secondary = '#F24C27';
const accent = '#F8BA42';
const light = '#FEFEFE';
const dark = '#3B3F42';
const theme = createMuiTheme({
palette: {
primary: buildPaletteFrom(primary),
secondary: buildPaletteFrom(secondary, accent),
light: buildPaletteFrom(light),
dark: buildPaletteFrom(dark),
common: {
white: light,
black: dark,
}
}
});