0

我正在使用 Material-UImakeStyles功能TypeScript

我在这里找到了如何做到这一点的解决方案并且它正在工作:

export interface StyleProps {
  md?: any;
}

const useStyles = makeStyles<Theme, StyleProps>({
  button: {
    width: ({ md }) => md && '50%',
  }
});

export default useStyles;

但我试图了解事情是如何运作的。

我不明白这<Theme, StyleProps>部分。我查看了 StackOverflow 上有关此的所有解决方案,没有人解释它。

有人可以澄清一下吗?

谢谢。

4

1 回答 1

1

这是我对 <Theme, StyleProps> 的简单解释

  • MaterialUI 的 makeStyles 方法使用泛型类型来定义你可以从他们的主题变量中使用什么,以及你想要分配的道具类型。

  • 主题类型导入自: import { Theme } from "@material-ui/core";

  • makeStyles() 返回您可以使用的主题值,“主题”是该主题值的类型定义。

代码示例:

#1 makeStyles 仅使用主题值:

const useStyles = makeStyles<Theme>((theme) => ({
  button: {
    background: theme.palette.background.paper,
    color: theme.palette.success.light
  }
}));

#2 makeStyles 使用主题值和你的道具:

const useStyles = makeStyles<Theme, StyleProps>((theme) => ({
  button: {
    background: theme.palette.background.paper,
    color: theme.palette.success.light,
    width: ({ md }) => "50%"
  }
}));

#3 makeStyles 只使用你的道具:

const useStyles = makeStyles<any /* <-- it doesn't matter what type u define here, because u doesn't use theme value*/, StyleProps>({
     button: {
       width: ({ md }) => "50%",
       background: "grey"
     }
    });

希望这个答案能有所帮助。:)

于 2022-01-08T20:31:11.303 回答