如果更改主题的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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句