Я создаю собственный компонент ссылки и передаю target = "_blank"
и rel = "noreferrer"
в качестве реквизита и использую {...props}
, назначенный <a>
.
const ExternalLinkTwo: React.FC<{
href: string;
children: ReactNode;
}> = ({ href, children, ...props }) => (
<a href = {href} {...props}>
{children}
</a>
);
export default function App() {
return (
<div className = "App">
<ExternalLinkTwo
href = "http://www.google.com"
target = "_blank" //throwing error here, why?
rel = "noreferrer"
>
Google 2
</ExternalLinkTwo>
</div>
);
}
Получение этой ошибки на реквизите target
(JSX attribute) target: string Type '{ children: string; href: string; target: string; rel: string; }' is not assignable to type 'IntrinsicAttributes & { href: string; children: ReactNode; } & { children?: ReactNode; }'. Property 'target' does not exist on type 'IntrinsicAttributes & { href: string; children: ReactNode; } & { children?: ReactNode; }'.ts(2322)
Какая ошибка вылетает? Вы должны включить полный текст ошибки в свой пост.
Если ваша цель — поддерживать обычный набор атрибутов <a>
, но сделать href
обязательным, используйте что-то вроде этого...
import { AnchorHTMLAttributes } from "react";
interface LinkProps extends AnchorHTMLAttributes<HTMLAnchorElement> {
href: string; // make href non-optional
}
const ExternalLinkTwo: React.FC<LinkProps> = ({ href, children, ...props }) => (
<a href = {href} {...props}>
{children}
</a>
);
Вам не нужно включать children
в свой тип реквизита. Он предоставляется автоматически через React.FC
.
Альтернативой является просто расширение Record<string, string>
, чтобы принять любые дополнительные атрибуты.
interface LinkProps extends Record<string, string> {
href: string;
}
@JenniferAlexis, не беспокойтесь. Надеюсь, вы не возражали, что я немного подчистил ваш вопрос. Должен помочь другим с той же проблемой найти его
К вашему сведению, вам не нужно определять
children
в реквизитах, вы автоматически получаете их изReact.FC