如何在react js中检查material ui主题的类型? (浅色或深色)

问题描述 投票:0回答:3

我想根据material ui主题的类型是浅色还是深色来创建某些条件 我怎样才能做到这一点?

reactjs types material-ui themes
3个回答
11
投票

以下不再起作用:

const isDarkTheme = useTheme().palette.type === 'dark';

试试这个:

 const isDarkTheme = useTheme().palette.mode === 'dark';

8
投票

您需要重新创建主题并更新值

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';

HOC

const ThemedComponent = withTheme(Component)
render() {
  const isDarkTheme = this.props.theme.palette.type === 'dark';
  return (...)
}

现场演示

Edit 64557510/how-can-i-check-the-type-of-material-ui-theme-in-react-js-light-or-dark


0
投票
  let isDark = useTheme().palette.mode === "dark";
© www.soinside.com 2019 - 2024. All rights reserved.