Vyhledávání na webu

javascript - React: Typescript nerozpoznává intrinsické atributy při rozšiřování HTMLAnchorElement


Mám jednoduchou komponentu značky anchor, která rozšiřuje nativní značku <a>.

Definoval jsem své rozhraní TypeScript tak, aby rozšiřovalo React.HTMLAttributes<HTMLAnchorElement>, ale když se pokusím použít komponentu A a předat vlastnosti jako rel a target, dostanu chyby IntrinsicAttributes.

Jak mohu správně rozšířit značku anchor?

Definice komponenty:

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>
  );
};

Pokusem o použití:

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

Chyba 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)

Odpověď č. 1

Použijte React.AnchorHTMLAttributes místo React.HTMLAttributes.

Zjistil jsem to prohlížením souboru node_modules/@types/react/index.d.ts a hledáním ve souborech pro rel?:

interface Props extends React.AnchorHTMLAttributes<HTMLAnchorElement> {

}

Související články