英文:
change background in MUI with linery condition
问题
我想有条件地更改背景,但这并没有起作用。
export const defaultTheme = createTheme({
palette: {
mode: "dark",
primary: {
light: "#757ce8",
main: "#3f50b5",
dark: "#464646",
contrastText: "#fff",
},
secondary: {
light: "#ff7961",
main: "#f44336",
dark: "#b200e2",
background: "#fff",
contrastText: "#000",
},
background: { default: defaultTheme.palette.mode === "dark" ? "#000" : "#fff" },
},
});
const MainTheme = ({ children }) => {
return (
<ThemeProvider theme={defaultTheme}>
<CssBaseline />
{children}
</ThemeProvider>
);
};
export default MainTheme;
我尝试在应用程序的其他部分像这样更改背景:
if (defaultTheme.palette.mode === "dark") {
defaultTheme.palette.background = { default: "#939393" };
} else {
defaultTheme.palette.background = { default: "#000" };
}
但这也没有起作用。
英文:
I want to change background conditionaly but that isn't work.
export const defaultTheme = createTheme({
},
palette: {
mode: "dark",
primary: {
light: "#757ce8",
main: "#3f50b5",
dark: "#464646",
contrastText: "#fff",
},
secondary: {
light: "#ff7961",
main: "#f44336",
dark: "#b200e2",
background: "#fff",
contrastText: "#000",
},
background: { default: defaultTheme.palette.mode=== "dark" ? "#000" : "#fff" },
},
});
const MainTheme = ({ children }) => {
return (
<ThemeProvider theme={defaultTheme}>
<CssBaseline />
{children}
</ThemeProvider>
);
};
export default MainTheme;
I try to change background in the other part of application like this:
if (defaultTheme.palette.mode === "dark") {
defaultTheme.palette.background = {default:"#939393"} ;
} else {
defaultTheme.palette.background = { default: "#000" };
}
and that didn't work too.
答案1
得分: 1
你必须提供两个主题 - 亮色和暗色,它们各自必须具有背景属性。在我们的应用程序中,您必须有一个切换按钮,其状态如下:
const [isLight, setLight] = useState(true);
// 其他一些内容
return (
<ThemeProvider theme={isLight ? defaultTheme : darkTheme}>
// 其他内容
</ThemeProvider>
);
这是一种非常常见的方法,但我希望您明白了要点。
英文:
You must provide two themes - light and dark, each of them must have props for background. Somewhere in our app your must have a toggle button with state like
const [isLight, setLight] = useState(true);
// some other stuff
return (
<ThemeProvider theme={isLight ? defaultTheme : darkTheme}>
// whatever
</ThemeProvider>
);
It's very common approach, but I hope you got the point.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论