You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MUI Styled组件TS报错:No overload matches this call 求解决方案

基于MUI Button自定义组件的TypeScript错误解决

问题

基于MUI Button封装自定义按钮时,出现TypeScript错误:No overload matches this call,按钮可正常渲染但报错始终存在。

原代码

import * as React from "react";
import Button, { ButtonProps } from "@mui/material/Button";
import { styled, Theme } from "@mui/material/styles";

interface DPWButtonProps extends ButtonProps {
  "dpw-variant": string;
}

const getStyles = (type: string, theme: Theme) => {
  const commonStyle: object = {};
  const themeStyles = {
    primary: {
      ...commonStyle,
      background: `red`
    },
    default: commonStyle
  };

  return themeStyles[type as keyof typeof themeStyles] || themeStyles.default;
};

const DWButton = styled(Button)<DPWButtonProps>(
  ({ "dw-variant": variant, theme }) => {
    return getStyles(variant, theme);
  }
);

export default DWButton;

使用方式

<DWButton dw-variant="primary">nnn</DWButton>

错误原因

  1. 属性名不一致:接口定义的是dpw-variant,但实际使用和styled回调中用的是dw-variant,类型不匹配。
  2. 自定义属性传递冲突:MUI的styled组件会默认把所有props传递给底层Button组件,但ButtonProps中没有dw-variant这个属性,导致TypeScript报错。

解决方法

1. 统一自定义属性名称

将接口、styled回调和使用时的属性名统一为dw-variant。

2. 排除自定义属性不传递给底层组件

使用styled的第二个参数配置shouldForwardProp,指定不把自定义属性传递给原始Button组件,避免类型冲突。

3. 优化类型安全性(可选)

把dw-variant的类型从宽泛的string改为字面量类型"primary" | "default",限制传入值的范围,提升类型检查的严谨性。

修正后的完整代码

import * as React from "react";
import Button, { ButtonProps } from "@mui/material/Button";
import { styled, Theme } from "@mui/material/styles";

// 统一属性名,并用字面量类型限定可选值
interface DWButtonProps extends ButtonProps {
  "dw-variant": "primary" | "default";
}

const getStyles = (type: "primary" | "default", theme: Theme) => {
  const commonStyle = {};
  const themeStyles = {
    primary: {
      ...commonStyle,
      background: `red`
    },
    default: commonStyle
  };

  return themeStyles[type];
};

const DWButton = styled(Button, {
  // 告诉styled组件不要将dw-variant传递给底层Button
  shouldForwardProp: (prop) => prop !== "dw-variant"
})<DWButtonProps>(
  ({ "dw-variant": variant, theme }) => {
    return getStyles(variant, theme);
  }
);

export default DWButton;

内容的提问来源于stack exchange,提问作者user19883277

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 09:00:41