简体   繁体   中英

Extending Material UI theme via Module Augmentation not working

I'm trying to add an "input" property to the background field within palette and then augment the Theme to account for types, like so:

export const lightTheme = createTheme(commonTheme, {
  palette: {
    mode: 'light',
    background: {
     default: '#FFFFFF',
     input: '#0000BB',
      ...
}
declare module '@mui/material/styles' {
  interface Theme {
    background: {
      input: React.CSSProperties['color'];
    };
  }

  interface ThemeOptions {
    background: {
      input: React.CSSProperties['color'];
    };
  }
}

However, when I try to access background via color: theme.palette.background.input , i get an error:

Property 'input' does not exist on type 'TypeBackground'.

Why is augmentation not adding the type to the background property?

To add, I also tried this which didn't change anything:

declare module "@mui/material/styles/createPalette" {
  interface CommonColors {
    background: {
      input: React.CSSProperties['color'];
    }
  }
}

You just need to extend the type TypeBackground as shown below:

declare module '@mui/material/styles' {
   interface TypeBackground {
        input: string;
    }
}

and then configure a new value for background.input

const theme = createTheme({
  ....
  palette: {
    background: {
      input: "#f60"
    }
  }
 ...
});

Finally, we can use it like this:

<Box sx={{ bgcolor: "background.input", width: 100, height: 100 }} />

The demo link

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM