我想根据material ui主题的类型是浅色还是深色来创建某些条件 我怎样才能做到这一点?
以下不再起作用:
const isDarkTheme = useTheme().palette.type === 'dark';
试试这个:
const isDarkTheme = useTheme().palette.mode === 'dark';
theme.palette.type
('light'
或 'dark'
)并将其传递给 ThemeProvider
以应用更改。
const defaultTheme = createMuiTheme({
palette: {
type: "light"
}
});
function App() {
const [theme, setTheme] = React.useState(defaultTheme);
const onClick = () => {
const isDark = theme.palette.type === "dark";
setTheme(
createMuiTheme({
palette: {
type: isDark ? "light" : "dark"
}
})
);
};
return (
<ThemeProvider theme={theme}>
<Card>
<Typography variant="h3">{theme.palette.type}</Typography>
<Button onClick={onClick}>Toggle theme</Button>
</Card>
</ThemeProvider>
);
}
然后,您可以使用钩子或 HOC 检查子组件中的主题类型
const isDarkTheme = useTheme().palette.type === 'dark';
const ThemedComponent = withTheme(Component)
render() {
const isDarkTheme = this.props.theme.palette.type === 'dark';
return (...)
}
let isDark = useTheme().palette.mode === "dark";