首页 > 解决方案 > 不能将 href 与 IconButtonProps 一起使用

问题描述

我正在尝试为 IconButton 创建一个包装器。我希望能够传递例如组件或 href 道具,但是在将 IconButtonProps 传递给它时我无法做到这一点。我怎么能做到这一点?

function NavIconLink(props : IconButtonProps) {
    const classes = useStyles();
    const { ...rest } = props;
    
    return (    
        <IconButton
            {...rest}
            href=""
            className={classes.buttonLink}
        >
            {props.children}
        </IconButton>
    )
}

标签: reactjstypescriptmaterial-ui

解决方案


解决方案

将类型上的组件类型的泛型设置IconButtonProps'a'

function NavIconLink(props: IconButtonProps<'a'>) {

解释

我能够复制您的错误。如果我只是设置一个href没有任何问题。但是,如果我设置href 传递所有内容,...rest那么我会收到No overload matches this call.错误消息。

错误跟踪很长,但这Overload 1 of 3是我们要解决的部分。那就是你会看到错误的地方

属性“onCopy”的类型不兼容。

类型“ ClipboardEventHandler<HTMLButtonElement> | undefined”不可分配给类型“ ClipboardEventHandler<HTMLAnchorElement> | undefined”。

简而言之,错误本质上是“您将href道具设置为好像元素是 an HTMLAnchorElement,但其他道具是用于 an HTMLButtonElement”。

我们需要确保所有的 props 都是正确的类型HTMLAnchorElement

如果您查看该IconButtonProps类型的源代码,您会发现它有一个D指定元素的泛型类型参数。

export type IconButtonProps<
  D extends React.ElementType = IconButtonTypeMap['defaultComponent'],
  P = {}
> = OverrideProps<IconButtonTypeMap<P, D>, D>;

您还将看到默认值为D--button这就是您收到HTMLButtonElement错误消息的原因。

export type IconButtonTypeMap<
  P = {},
  D extends React.ElementType = 'button'
> = ExtendButtonBaseTypeMap<{
  props: P & {
    ...
  };
  defaultComponent: D;
  ...
}>;

所以当你使用这种类型时,你需要指定你的...restprops 应该是一个a组件而不是一个button. 将第一个泛型设置IconButtonProps'a',您的错误将消失。

function NavIconLink({ children, ...rest } : IconButtonProps<'a'>) {
  return (
    <IconButton
      { ...rest } // props for a link
      href="" // also a prop for a link
    >
      {children}
    </IconButton>
  )
}

推荐阅读