使用React Material-UI构建卡片时遇TypeScript错误:sx属性不存在于CardProps
问题根源与解决方法
你导错包了!你用的@material/react-card是Google的Material Components for React(MDC)库,而MUI官网的示例是基于@mui/material(原Material-UI)的,这俩不是同一个库——sx属性是@mui/material独有的配置属性,MDC React里根本没有这个属性,所以才会报类型错误。
具体解决步骤
- 替换依赖包(如果之前装了错误的包,先卸载再安装正确的):
# 卸载错误的MDC包(可选,如果你之前装了的话) npm uninstall @material/react-card # 安装MUI核心包及sx依赖的样式库 npm install @mui/material @emotion/react @emotion/styled - 修正组件导入路径,所有组件都从
@mui/material导入,同时补上缺失的Button和Typography导入:import { Card, CardActions, CardContent, CardMedia, Button, Typography } from '@mui/material'; - 你的组件代码逻辑没问题,导入修正后,
sx属性就能正常使用了,完整代码如下:import { Card, CardActions, CardContent, CardMedia, Button, Typography } from '@mui/material'; function LizardCard() { return ( <Card sx={{ maxWidth: 345 }}> <CardMedia sx={{ height: 140 }} image="/static/images/cards/contemplative-reptile.jpg" title="green iguana" /> <CardContent> <Typography gutterBottom variant="h5" component="div"> Lizard </Typography> <Typography variant="body2" color="text.secondary"> Lizards are a widespread group of squamate reptiles, with over 6,000 species, ranging across all continents except Antarctica </Typography> </CardContent> <CardActions> <Button size="small">Share</Button> <Button size="small">Learn More</Button> </CardActions> </Card> ); } export default LizardCard;
注意事项
别搞混@mui/material(MUI,原Material-UI)和@material/react-*(MDC React)这两个库,它们的API设计差异很大,以后查阅文档时要对应好依赖包的来源。
内容的提问来源于stack exchange,提问作者cluis92
相关产品推荐
相关产品推荐

