我正在使用:
我正在尝试复制SimpleListMenu的material-ui演示,但是最后一个编译错误,我不知道该怎么做。
import React from 'react';
import List from '@material-ui/core/List';
import ListItem from '@material-ui/core/ListItem';
import ListItemText from '@material-ui/core/ListItemText';
import MenuItem from '@material-ui/core/MenuItem';
import Menu from '@material-ui/core/Menu';
import {StyleRulesCallback, Theme, WithStyles} from "@material-ui/core";
import withStyles from "@material-ui/core/styles/withStyles";
const styles: StyleRulesCallback<"root"> = (theme: Theme) => ({
root: {
width: '100%',
maxWidth: 360,
backgroundColor: theme.palette.background.paper,
},
});
const options = [
'Show some love to Material-UI',
'Show all notification content',
'Hide sensitive notification content',
'Hide all notification content',
];
type Props = WithStyles<typeof styles> & {
classes: {
root: string
}
};
type State = {
anchorEl: EventTarget & HTMLElement | null
selectedIndex: number
};
class SimpleListMenu extends React.Component<Props, State> {
state = {
anchorEl: null,
selectedIndex: 1,
};
handleClickListItem = (event: React.MouseEvent<HTMLElement>) => {
this.setState({ anchorEl: event.currentTarget });
};
handleMenuItemClick = (event: React.MouseEvent<HTMLElement>, index: number) => {
this.setState({ selectedIndex: index, anchorEl: null });
};
handleClose = () => {
this.setState({ anchorEl: null });
};
render() {
const { anchorEl } = this.state;
return (
<div className={this.props.classes.root}>
<List component="nav">
<ListItem
button
aria-haspopup="true"
aria-controls="lock-menu"
aria-label="When device is locked"
onClick={this.handleClickListItem}
>
<ListItemText
primary="When device is locked"
secondary={options[this.state.selectedIndex]}
/>
</ListItem>
</List>
<Menu
id="lock-menu"
anchorEl={anchorEl}
open={Boolean(anchorEl)}
onClose={this.handleClose}
>
{options.map((option, index) => (
<MenuItem
key={option}
disabled={index === 0}
selected={index === this.state.selectedIndex}
onClick={event => this.handleMenuItemClick(event, index)}
>
{option}
</MenuItem>
))}
</Menu>
</div>
);
}
}
export default withStyles(styles, {withTheme: true })<Props>(SimpleListMenu); // Compile error here
我收到此错误:
TS2344: Type 'Props' does not satisfy the constraint 'ComponentType<ConsistentWith<Props, boolean>>'.
Type 'Props' is not assignable to type 'StatelessComponent<ConsistentWith<Props, boolean>>'.
Type 'Props' provides no match for the signature '(props: ConsistentWith<Props, boolean> & {children? ReactNode;}, context?: any): ReactElement<any> | null'.
我已经尝试了很多方法来解决这个错误。我主要关注此guy's example。任何人都有见识?
ETA:我尝试编译stackoverflow问题中的代码,并且遇到与我相同的编译错误。我也尝试了Typescript type error in component returned by withStyles() 中的几乎每个示例,并且遇到了相同的打字稿错误。所以它一定与我的安装有关吗?
答案 0 :(得分:0)
尝试遵循https://material-ui.com/guides/typescript/
中的键入模式特别是
type Props = WithStyles<typeof styles> & {
classes: {
root: string
}
};
不遵循建议。
可以在https://next--material-ui.netlify.com/demos/menus/#selected-menus上找到菜单演示的工作示例(单击显示源,然后切换到TS)