如果我更改主题的1种颜色,则主题保持不变。
但是,如果我尝试更新调色板类型,它将无法正常工作。它可以创建一个新主题。但是在那种情况下,我会放弃之前的所有修改。
当前行为
如果覆盖颜色,则调色板类型保持原样。 如果我覆盖调色板类型。没用 如果使用新的调色板类型创建新主题,则可以使用,但是会丢失先前的更改。
预期行为 更改调色板类型后,我仍然应该看到我的原色。
复制步骤
步骤:
答案 0 :(得分:1)
您遇到问题是因为尝试使用空对象或使用Material-ui中完全生成的主题对象。
一个简单的解决方案是通过上下文传递当前主题,并基于该主题创建一个新主题。这样一来,material-ui便可以根据dark / light类型生成主题的所有其他值。
function ThemeCustomProvider({ children }) {
const [theme, setTheme] = React.useState(defaultTheme());
return (
<ThemeProvider theme={createMuiTheme(theme)}>
<ThemeSetContext.Provider value={{ theme, setTheme }}>
<CssBaseline />
{children}
</ThemeSetContext.Provider>
</ThemeProvider>
);
}
在您的组件中,我们将使用lodash/merge
将旧主题与新值合并
const { theme, setTheme } = useThemeSetContext(); // The function taht will update the theme
const handleChangeDark = () => {
const newTheme = merge(
{}, // Use a new object. We don't mutate data in React
theme, // Copy the old theme values
{
palette: {
type: theme.palette.type === "light" ? "dark" : "light"
}
}
);
setTheme(newTheme); // Update the theme with the new theme that only has change dark type
setMessage(
"The theme change between dark and light, but overrides the primary color, so the primary color are always blue."
);
};
const handleChangeColor = () => {
const newTheme = merge(
{},
theme,
{
palette: {
primary: {
main: getRandomColor() // The new value
}
}
}
);
setTheme(newTheme); // Update the theme with the new object that keeps the previous values like palette type
setMessage(
"The theme change the primary color, keeping the theme dark/light theme."
);
};
这是您的代码和框,其中包含以下更改:
https://codesandbox.io/s/so-material-ui-changetheme-type-qdbe9