使用带有Typescript的材质UI makeStyles

时间:2020-06-18 17:49:21

标签: reactjs typescript material-ui material-design typescript-typings

我为classes prop创建了一个单独的文件,例如MuiAlert

如何告诉makeStyles仅允许您使用Alert类?

以下方法有效,但我相信必须有更好的方法。所以如果将root重命名为roott,则会收到'roott' does not exist in type 'Partial<Record<AlertClassKey, any>>'

的错误消息

游乐场示例:https://codesandbox.io/s/typescript-react-material-ui-3t7ln?file=/src/index.ts

import { Theme, makeStyles } from "@material-ui/core";
import { AlertClassKey } from "@material-ui/lab/Alert";

export const useAlertClasses = makeStyles<Theme>(
  (): Partial<Record<AlertClassKey, any>> => ({
    root: {
      borderRadius: 3,
    }
}));

1 个答案:

答案 0 :(得分:0)

我的解决方案:

import { Theme } from "@material-ui/core/styles/createMuiTheme";
import { StyleRules } from "@material-ui/core/styles/withStyles";
import { makeStyles } from "@material-ui/core/styles";
import { createStyles } from "@material-ui/core/styles";

import { AlertClassKey } from "@material-ui/lab/Alert";

export const alertOverrides = (
    theme: Theme
): Partial<StyleRules<AlertClassKey>> => {
    return {
        root: {
            backgroundColor: "red !important",
        },
    };
};

export const useAlertStyles = makeStyles<Theme, {}>(
    (theme) => {
        return createStyles(alertOverrides(theme) as never);
    },
    { name: "MuiAlert" }
);