https://coding.imooc.com/learn/questiondetail/203318.html 问题的延伸

来源:4-11 精益求精 - Buton 组件编码第二部分

ywang04

2021-01-26

老师 有同学问到HTMLElement和HTMLButtonElement 这两个泛型的区别。

React.ButtonHTMLAttributes<HTMLElement>
React.ButtonHTMLAttributes<HTMLButtonElement>

你的回答我可以理解 但接着我发现如果使用HTMLButtonElement 这个泛型 会报如下错误

我的理解是 源码里 HTMLButtonElement 也是继承HTMLElement 为什么会报
Parameter ‘e’ implicitly has an ‘any’ type. ts(7006) 这个错误?希望老师帮忙解答下 谢谢

图片描述

写回答

1回答

张轩

2021-01-26

同学你好 是这样的 应该是你只改了

type NativeButtonProps = BaseButtonProps & ButtonHTMLAttributes<HTMLButtonElement>

然后 Anchor 的并没有改,这个时候,后面的

export type ButtonProps = Partial<NativeButtonProps & AnchorButtonProps> 
两者没法合并在一起,会造成两种不同的类型
鼠标移动上去是可以看出来的

//img1.sycdn.imooc.com/szimg/600fedc30966f76720260266.jpg

你可以把 Anchor 也改成一样的

type AnchorButtonProps = BaseButtonProps & AnchorHTMLAttributes<HTMLButtonElement>

这样就没问题了,但是这样改好吗?因为 a 链接可有可能不是一个 button 元素啊。所以这里你就要斟酌,看看是否要这样修改了

1
1
ywang04
非常感谢!
2022-09-25
共1条回复

React18+TS高仿AntD从零到一打造组件库

设计,开发,测试,发布再到 CI/CD,从0到1造轮子

2128 学习 · 959 问题

查看课程