长话短说,typescript 提示每个material-ui 组件上缺少属性类
。换句话说,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;
我的工具栏
出现错误,并显示以下消息
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 属性
style 和 className 属性
<AppBar position="static" style={exampleStyleObj} className={exampleClass} >
我遵循使用material-ui文档中的withStyle
装饰器的样式方法
CSS IN JS & Over
https://material-ui-next.com/customization/css-in-js/Overrides
https://material-ui-next.com/customization/overrides/Typescript Material-UI guides
https://material-ui-next.com/guides/typescript/
我正在使用, [email protected] [email protected]
我检查了其他地方是否有相同的问题和答案,甚至检查了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 的 withStyle HOC 提供了很好的支持。 .
但是您已使用 export default withStyles(styles)(YourComponent)
导出组件,否则 TypeScript 仍会提示:
TS2741: Property 'classes' is missing in type '{}' but required in type '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);
关于reactjs - MUI 组件的类型中缺少 Typescript Material UI 属性 'classes',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47466060/