如何在Astro TypeScript组件中继承<a>标签的通用HTML属性?
在Astro中复用HTML标签原生属性类型的方法
当然可以!Astro 内置了对应所有HTML元素的属性类型定义,你不需要手动重复写href、target这些原生属性,直接扩展官方提供的类型即可:
- 从
astro/types导入对应<a>标签的属性类型HTMLAnchorAttributes - 让你的
Props接口扩展这个类型
修改后的完整代码如下:
--- import type { HTMLAnchorAttributes } from 'astro/types'; export interface Props extends HTMLAnchorAttributes {} const props = Astro.props; --- <a {...props}> <slot /> </a>
如果之后需要给组件添加自定义属性,直接在Props接口里追加即可,比如:
export interface Props extends HTMLAnchorAttributes { isExternal?: boolean; }
这样既保留了<a>标签的所有原生属性支持,又能灵活扩展自定义属性,和React里React.HTMLAttributes<HTMLAnchorElement>的用法逻辑完全一致。
内容的提问来源于stack exchange,提问作者Sang
相关产品推荐
相关产品推荐

