reactjs - 为什么我不能为我的多态组件属性使用默认初始化程序?
问题描述
我正在 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 链接,您可以在其中查看错误并使用代码
有人可以解释一下区别吗?为什么它以一种方式工作而不是另一种方式,我该怎么做才能使默认初始化程序工作?
解决方案
推荐阅读
- javascript - 通过 MutationObserver 遍历多个 addedNodes 并获取 target.innerText
- c# - Visual Studio for mac 损坏(无法编译)
- python - 尝试使用 pypy 运行文件导致“'pypy' 未被识别为内部或外部命令、可运行程序或批处理文件”
- javascript - ReactJS 中的 onClick 方法
- jquery - 父 DIV 悬停时更改图像和文本属性
- arm - 通过 LM3S811 Qemu Simulation 中的中断在 UART 中回显数据
- python - Traceback(最近一次通话最后一次):文件“
",第 1 行,在 NameError:名称“db”未定义 - django-settings - Django 将额外安装的应用程序放在不同的设置文件中
- html - 在滚动容器内使用可见宽度
- c++ - QT安装程序框架-在线更新执行后如何添加自定义脚本