长话短说,打字稿抱怨每个材料UI组件上缺少property classes
。换句话说,Typescript 强制classes
属性存在于几乎每个 material-ui 组件中。这是使用ts-loader
编译 webpack 时的错误消息,
我有以下代码,
标题.tsx
import AppBar from 'material-ui/AppBar';
import * as React from 'react';
import { withStyles } from 'material-ui/styles/index';
import Toolbar from 'material-ui/Toolbar';
import Typography from 'material-ui/Typography';
const decorate = withStyles((theme) => ({
header: {
paddingTop: theme.spacing.unit,
width: '100%',
},
}));
const AppBarTypographyStyle = {
color: 'white',
fontSize: '1.6rem',
};
const Header = decorate(({classes}) => (
<header>
<AppBar position="static" classes={{root: classes.header}}>
<Toolbar>
<Typography style={AppBarTypographyStyle} classes={{}} color="inherit" type="title">
OLIVE
</Typography>
</Toolbar>
</AppBar>
</header>
));
export default Header;
我有以下消息Toolbar
错误
TS2322: Type '{ children: Element; }' is not assignable to type 'IntrinsicAttributes & ToolbarProps & { children?: ReactNode; }'.
Type '{ children: Element; }' is not assignable to type 'ToolbarProps'.
Property 'classes' is missing in type '{ children: Element; }'
对于AppBar
和Typography
我没有收到错误,因为我添加了classes property
,并在function decorator
中定义了我的样式和一个空对象;但是,不可能只使用style & className properties
<AppBar position="static" style={exampleStyleObj} className={exampleClass} >
我遵循使用材料 UI 文档中的装饰器withStyle
样式方法
CSS in JS&Over
https://material-ui-next.com/customization/css-in-js/覆盖
https://material-ui-next.com/customization/overrides/打字稿材料-用户界面指南
https://material-ui-next.com/guides/typescript/
我正在使用, typescript@2.4.0 材料-ui@1.0.0-β.21
我已经检查了其他地方是否有相同的问题和答案,甚至检查了 material-ui 源代码并发现了以下内容,
/**
* All standard components exposed by `material-ui` are `StyledComponents` with
* certain `classes`, on which one can also set a top-level `className` and inline
* `style`.
*/
export type StandardProps<C, ClassKey extends string, Removals extends keyof C = never> =
& Omit<C & { classes: any }, 'classes' | Removals>
& StyledComponentProps<ClassKey>
& {
className?: string;
style?: Partial<React.CSSProperties>;
}
StandardProps
是大多数ComponentProps interface
扩展的内容(例如,AppBarProps)。然而,到目前为止,我没有多少运气解决这些问题。
请帮忙!
在TypeScript 4中,现在对Material UI的Style HOC有了很好的支持。
但是你已经使用export default withStyles(styles)(YourComponent)
导出你的组件,否则TypeScript仍然会抱怨:
TS2741:类型"{}"中缺少属性"类",但在类型"Props"中是必需的。
下面是一个模板,显示了如何使用TypeScript 4完成此操作:
import React from 'react';
import {createStyles, Theme, withStyles, WithStyles} from '@material-ui/core';
const styles = (theme: Theme) =>
createStyles({
// ...
});
interface Props extends WithStyles<typeof styles> {}
const YourComponent: React.FC<Props> = (props: Props): JSX.Element => {
const {classes} = props;
return (
// ...
);
};
export default withStyles(styles)(YourComponent);
我想回答我的问题。感谢来自material-ui gitter的Tom Crockett。
由于材料-UI 组件上的类型差异,使用 Typescript2.4.0
将不起作用。但是,2.4.2
补丁可以解决问题。