首页 > 解决方案 > 为什么我不能为我的多态组件属性使用默认初始化程序?

问题描述

我正在 TypeScript 中编写一个多态 React 组件,如下所示:

interface Props<C extends React.ElementType> {
  as?: C;
  children: React.ReactNode;
  size?: "mini" | "small" | "medium" | "large";
  onClick?: (event: React.MouseEvent<HTMLButtonElement, MouseEvent>) => void;
}

type ButtonProps<C extends React.ElementType> = Props<C> &
  Omit<React.ComponentPropsWithRef<C>, keyof Props<C>>;

export const Button = <C extends React.ElementType = "button">({
  children,
  as: Component = "button",
  size = "medium",
  onClick,
  ...restProps
}: ButtonProps<C>) => {
  return (
    <Component {...restProps} className={`button-${size}`} onClick={onClick}>
      {children}
    </Component>
  );
};

但是上面的代码出现编译错误。主要错误是as: Component = "button"在线。错误是

Type '"button"' is not assignable to type 'C'.
  '"button"' is assignable to the constraint of type 'C', but 'C' could be instantiated with a different subtype of constraint 'ElementType<any>'.ts(2322)

我可以通过不使用默认初始化程序来解决此问题,如下所示:

export const Button = <C extends React.ElementType = "button">({
  children,
  as,
  size = "medium",
  onClick,
  ...restProps
}: ButtonProps<C>) => {
  const Component = as || "button";

  return (
    <Component {...restProps} className={`button-${size}`} onClick={onClick}>
      {children}
    </Component>
  );
};

TypeScript Playground 链接,您可以在其中查看错误并使用代码

有人可以解释一下区别吗?为什么它以一种方式工作而不是另一种方式,我该怎么做才能使默认初始化程序工作?

标签: reactjstypescript

解决方案


推荐阅读