typescript - Type ไม่ตรงกับลายเซ็นที่ใช้กับ withStyles
ในขณะที่พยายามแปลงแอป React ของฉันเป็น TypeScript ฉันก็ได้รับข้อผิดพลาดด้านล่างอยู่ตลอดและพยายามเท่าไหร่ก็ไม่สามารถเข้าใจได้ว่ามันหมายความว่าอะไร แอปทำงานได้ปกติใน JavaScript ธรรมดา ฉันกำลังใช้ 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)
คำตอบ #1
โปรดดูคู่มือ TypeScript โดยเฉพาะส่วนเกี่ยวกับ withStyles (ลิงก์ถูกลบ)
คอมโพเนนต์แบบคลาสค่อนข้างยุ่งยากมากกว่า เนื่องจากข้อจำกัดปัจจุบันในการสนับสนุนตัวตกแต่งของ TypeScript ทำให้
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() {
// ...
}
}
);
