How can I extend Color Palette in Material UI with Typescript

隐身守侯 提交于 2020-12-31 16:26:14

问题


I am new on react and typescript. I am trying to extend the color palette on a global theme.

in my themeConitainer.tsx

import { ThemeOptions } from '@material-ui/core/styles/createMuiTheme';

declare module '@material-ui/core/styles/createPalette' {
  // allow configuration using `createMuiTheme`
  interface Palette {
    accent: PaletteColor
  }
  interface PaletteOptions {
    accent: PaletteColorOptions,
    tertiary: PaletteColorOptions
  }
};

const ThemeContainer: React.FunctionComponent<Props> = (props, themeOptions: ThemeOptions) => {
  const { children } = props;

  const theme = useMemo(() => {
    const nextTheme = createMuiTheme({
      ...themeOptions,
      palette: {
        accent: {
          main: '#ff0000'
        },
      }
    });

    return nextTheme;
  });

  return <ThemeProvider theme={theme}>{children}</ThemeProvider>;
};

export default ThemeContainer;


but on my component, there was an error.

No overload on this call.

Thank you in advance.


回答1:


not 100% sure in TS, but it works for me like this:

declare module "@material-ui/core/styles/createPalette" {
  interface Palette {    
    lightWarning: Palette["primary"];
  }
  

  interface PaletteOptions {    
    lightWarning: PaletteOptions["primary"];
  } 

}

Find a brief introduction at the projekt homepage: https://material-ui.com/guides/typescript/#customization-of-theme

Or in this article: https://medium.com/javascript-in-plain-english/extend-material-ui-theme-in-typescript-a462e207131f




回答2:


The short answer is that you can't (and you shouldn't) do this.

The long answer contains the following explanation:

Material UI is (one of) React's implementations of the Material Design concept.

Material Design is a design language that Google developed in 2014. Expanding on the "card" motifs that debuted in Google Now, Material Design uses more grid-based layouts, responsive animations and transitions, padding, and depth effects such as lighting and shadows.

As part of Material Design you have the color system, which contains a primary/secondary (and a variant for each of them).
You also have the dark/light theme which you can control, and each of them also have primary/secondary colors.

If you need more colors - you probably don't follow the idea of Material Design.

You can always use CSS/Variables/Styled components for extra design options, but in general you shouldn't.



来源:https://stackoverflow.com/questions/61097813/how-can-i-extend-color-palette-in-material-ui-with-typescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!