TypeScript と Material-UI withStyles
ググって最初に出てきたのを試したけどだめだったが、material-ui のリポジトリ見てたら TypeScript のサンプルがあったので、これを見ながら使ってみる。
インストール
まずは material-ui をインストール:
->|bash| yarn add @material-ui/core
バージョンはこんなかんじ:
->|json|
"dependencies": {
"@material-ui/core": "^1.5.1",
},
"devDependencies": {
"typescript": "^3.0.1"
},
TypeScript v2.7 くらいでやったときはコンパイルエラー起きたので注意。
withStyles
そのまま使うならなんにも考えなくていいんだけど、withStylesで classes をインジェクションしたい場合、ちょっとトリッキーな使い方になる。
createThemeは型コンパイルを行うだけで、ランタイム時には何もしない関数。WithStylesで classes に型を提供する。
->|tsx|
import Button from "@material-ui/core/Button";
import { createStyles, withStyles, WithStyles } from "@material-ui/core/styles";
import { Theme } from "@material-ui/core/styles/createMuiTheme";
import * as React from "react";
interface OwnProps {
label: string;
}
const styles = (theme: Theme) => {
return createStyles({
button: {
margin: theme.spacing.unit
}
});
};
type MyButtonProps = OwnProps & WithStyles<typeof styles>;
const MyButton: React.SFC<MyButtonProps> = ({ label, classes }) => {
return (
<Button color="primary" className={classes.button}>
{label}
</Button>
);
};
export default withStyles(styles)(MyButton);