admin管理员组

文章数量:1125625

I am trying to use the custom styled feature from MUI library -

As far I understand from the documentation, this should provide support for a different theme by providing the defaultTheme.

For some reason I cannot make it work properly. If I have a ThemeProvider in the tree and have custom styled with a different theme, the theme in the customStyled is still the theme provided to ThemeProvider

Implementation below - Stackblitz HERE

import { createStyled } from '@mui/system';
import { Button, createTheme, ThemeProvider } from '@mui/material';

const theme1 = createTheme({
  palette: {
    primary: {
      main: '#FF0000',
    },
  },
});

const theme2 = createTheme({
  palette: {
    primary: {
      main: '#04FF00',
    },
  },
});

const customStyled = createStyled({ defaultTheme: theme2 });

const CustomButton = customStyled(Button)(({ theme }) => {
  return {
    backgroundColor: theme.palette.primary.main,
  };
});

function App() {
  return (
    <>
      <CustomButton variant="contained">Custom</CustomButton> // HERE the color is from theme2
      <ThemeProvider theme={theme1}>
        <CustomButton variant="contained">Custom</CustomButton> // HERE the color is from theme1 
        <Button variant="contained">Button</Button>
      </ThemeProvider>
    </>
  );
}

Is there a way for the customStyled to not take into consideration the theme1 which is provided to ThemeProvider?

Shouldn't this be the use case for this defaultTheme override? To be able to bypass the theme provided to the provider and use a different one?

Thanks!

本文标签: reactjsMUI createStyled defaultTheme overrideStack Overflow