无法将component属性传递给Styled MUI Button的TypeScript问题
问题根源
你手动为styled(Button)指定了泛型ButtonProps,但component是MUI styled组件提供的通用属性,并不属于原生的ButtonProps类型,因此TypeScript会判定该属性不存在。
解决方案
有两种简单的修复方式:
方式1:让TypeScript自动推断类型(推荐)
删除手动指定的泛型,styled工具会自动结合原始组件的属性和styled组件的通用属性生成正确类型:
import { styled, Button } from '@mui/material'; const SecondaryButton = styled(Button)(({ theme }) => ({ // 你的自定义样式代码 })); export default SecondaryButton;
方式2:显式扩展类型
如果需要手动指定泛型,将ButtonProps与styled组件的通用属性结合:
import { styled, Button, ButtonProps } from '@mui/material'; import type { ReactElement } from 'react'; const SecondaryButton = styled(Button)<ButtonProps & { component?: React.ElementType }>(({ theme }) => ({ // 你的自定义样式代码 })); export default SecondaryButton;
或者使用MUI提供的StyledProps类型简化:
import { styled, Button, ButtonProps } from '@mui/material'; import type { StyledProps } from '@mui/material/styles'; const SecondaryButton = styled(Button)<StyledProps<ButtonProps>>(({ theme }) => ({ // 你的自定义样式代码 }));
修复后,你原来的使用代码即可正常编译,不会再出现component属性不存在的错误。
内容的提问来源于stack exchange,提问作者phe
相关产品推荐
相关产品推荐

