【问题标题】:React: Typescript not recognizing intrinsic attributes when extending HTMLAnchorElementReact:Typescript 在扩展 HTMLAnchorElement 时无法识别内在属性
【发布时间】:2020-11-17 19:08:57
【问题描述】:

我有一个简单的锚标签组件,它扩展了原生的<a> 标签。

我已经定义了我的 typescript 接口来扩展 React.HTMLAttributes<HTMLAnchorElement>,但是当我尝试使用组件 A 并传递像 reltarget 这样的道具时,我得到了 IntrinsicAttributes 错误。

如何正确扩展锚标签?

组件定义:

interface Props extends React.HTMLAttributes<HTMLAnchorElement> {
  href: string;
  className?: string;
}

export const A: FC<Props> = ({ href, className, children, ...rest }) => {
  const baseClasses = "text-mb-green-200";
  const classes = `${baseClasses} ${className ? className : ""}`;

  return (
    <a {...rest} href={href} className={classes}>
      {children}
    </a>
  );
};

尝试使用:

<A {...rest} href={href} className={classes} rel={rel} target={target}>
   {children}
</A>

TS 错误:

Type '{ children: ReactNode; href: string; className: string; target: string; }' is not assignable to type 'IntrinsicAttributes & Props & { children?: ReactNode; }'.
  Property 'rel' does not exist on type 'IntrinsicAttributes & Props & { children?: ReactNode; }'.ts(2322)

【问题讨论】:

    标签: javascript html reactjs typescript intrinsicattributes


    【解决方案1】:

    使用React.AnchorHTMLAttributes 而不是React.HTMLAttributes

    我通过查看node_modules/@types/react/index.d.ts 文件并搜索rel?: 发现了这一点

    interface Props extends React.AnchorHTMLAttributes<HTMLAnchorElement> {
    
    }
    

    【讨论】:

      猜你喜欢
      • 2019-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-05
      相关资源
      最近更新 更多