makeStyles with TypeScript - 传递道具来制作样式解释

makeStyles with TypeScript - pass props to make styles explanation

我正在使用 Material-UI makeStyles 函数和 TypeScript

我在这里找到了解决方法,它正在运行:

export interface StyleProps {
  md?: any;
}

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

export default useStyles;

但我正在努力了解事情是如何运作的。

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

有人可以澄清一下吗?

谢谢。

这是我对的简单解释

  • MaterialUI 中的 makeStyles 方法使用通用类型来定义您可以从其主题变量中使用的内容,以及您要分配的道具类型。

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

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

代码示例:

#1 makeStyles 仅使用主题值:

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

#2 使用主题值和您的道具制作样式:

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"
     }
    });

希望这个回答能对您有所帮助。 :)