使用styled定制MUI组件后无法传递props的TypeScript报错问题
解决@mui/styles styled定制组件的TypeScript类型错误
问题根源
@mui/styles 的 styled 方法不会自动继承目标组件(包括通过 component 属性替换的组件)的全部Props类型,必须手动显式声明泛型来合并所需的属性类型,否则TypeScript无法识别额外传递的Props。
1. 定制容器作为Link使用时to属性不存在的解决方法
当你把定制的FeaturedCardContainer(基于Box)作为Link组件使用时,需要合并Box和Link的Props类型:
import { Box, BoxProps } from '@mui/material'; import { Link, LinkProps } from '@mui/material'; import { styled } from '@mui/styles'; // 合并Box与Link的Props类型 type FeaturedCardContainerProps = BoxProps & LinkProps; const FeaturedCardContainer = styled(Box)<FeaturedCardContainerProps>(({ theme }) => ({ // 你的自定义样式 width: '100%', cursor: 'pointer', // ...其他样式 })); // 使用示例 <FeaturedCardContainer component={Link} to="/article/123"> {/* 卡片内容 */} </FeaturedCardContainer>
或者更简洁的方式:直接在styled中通过attrs指定component为Link,并继承Link的Props:
const FeaturedCardContainer = styled(Box).attrs({ component: Link })<LinkProps>(({ theme }) => ({ // 自定义样式 }));
2. StyledCardMedia的component="img"和alt属性报错的解决方法
当给CardMedia指定component="img"时,需要合并CardMediaProps和img元素的原生HTML属性类型:
import { CardMedia, CardMediaProps } from '@mui/material'; import { styled } from '@mui/styles'; // 合并CardMediaProps与img元素的属性类型 type StyledCardMediaProps = CardMediaProps & React.ImgHTMLAttributes<HTMLImageElement>; const StyledCardMedia = styled(CardMedia)<StyledCardMediaProps>(({ theme }) => ({ // 你的自定义样式 height: 200, borderRadius: theme.shape.borderRadius, // ...其他样式 })); // 使用示例 <StyledCardMedia component="img" src="/featured-image.jpg" alt="特色文章封面" />
如果预先通过attrs设置component="img",可以直接继承img的属性类型:
const StyledCardMedia = styled(CardMedia).attrs({ component: 'img' })<React.ImgHTMLAttributes<HTMLImageElement>>(({ theme }) => ({ // 自定义样式 }));
内容的提问来源于stack exchange,提问作者Chandraprakash Darji
相关产品推荐
相关产品推荐

