在尝试将我的React应用程序转换为打字稿时,我不断收到下面的错误,而对于我的生活,我无法弄清楚它的含义。该应用程序在普通JS中运行良好。我正在使用material-ui@next
TS2345: Argument of type 'typeof ApplicationMenu' is not assignable to parameter of type 'ComponentType<AppMenuProps & WithStyles<"root" | "flex" | "menuButton" | "appBar" | "loginButton">>'.
Type 'typeof ApplicationMenu' is not assignable to type 'StatelessComponent<AppMenuProps & WithStyles<"root" | "flex" | "menuButton" | "appBar" | "loginBu...'.
Type 'typeof ApplicationMenu' provides no match for the signature '(props: AppMenuProps & WithStyles<"root" | "flex" | "menuButton" | "appBar" | "loginButton"> & { children?: ReactNode; }, context?: any): ReactElement<any> | null'.
产生此错误的代码位于
之下export interface AppMenuProps {
classes: Record<string, string | undefined>
}
const styles = (theme : Theme) => ({
root: {
width: '100%',
},
flex: {
flex: 1,
},
menuButton: {
marginLeft: -12,
marginRight: 20,
},
appBar: {
background: theme.palette.common.black,
color: theme.palette.common.white,
},
loginButton: {
color: theme.palette.common.white
}
});
class ApplicationMenu extends Component<AppMenuProps, {}> {
render() {
const {classes} = this.props;
return (
<div className={classes.root}>
<AppBar position="static" classes={{root: classes.appBar}}>
<Toolbar>
<IconButton className={classes.menuButton} color="primary" aria-label="Menu">
<MenuIcon/>
</IconButton>
<Typography type="title" color="inherit" className={classes.flex}>
Supportworks Dashboard
</Typography>
<Button classes={{root: classes.loginButton}}>Login</Button>
</Toolbar>
</AppBar>
</div>
);
}
}
export default withStyles(styles)(ApplicationMenu)
答案 0 :(得分:4)
请参阅TypeScript guide,尤其是section on withStyles:
类组件有点麻烦。由于current limitation in TypeScript's decorator support,
withStyles
不能用作类装饰器。相反,我们装饰一个类组件......
你需要做这样的事情:
import { WithStyles } from 'material-ui/styles';
export interface AppMenuProps {
classes: Record<string, string | undefined>
}
const styles = (theme : Theme) => ({
root: {
width: '100%',
},
flex: {
flex: 1,
},
menuButton: {
marginLeft: -12,
marginRight: 20,
},
appBar: {
background: theme.palette.common.black,
color: theme.palette.common.white,
},
loginButton: {
color: theme.palette.common.white
}
});
const ApplicationMenu = decorate(
class extends React.Component<AppMenuProps & WithStyles<'root' | 'flex' | 'menuButton' | 'appBar' | 'loginButton'>> {
render() {
// ...
}
}
);