我嘗試使用“Link”元素作為我的自定義反應組件,我用打字稿修改它以添加更多功能,但每次在我的專案中使用它時,它都會讓我撰寫一個帶有道具名稱的屬性,其中包含其他一些特性 :
下面一行是我的打字稿運行時錯誤:
Type '{ link: string; title: string; }' is missing the following properties from type 'DetailedReactHTMLElement<{ onm ouseEnter?: MouseEventHandler<Element> | undefined; onClick?: MouseEventHandler<Element> | undefined; href?: string | undefined; ref?: any; }, HTMLElement>': type, ref, props, keyts(2739)
我寫了我的自定義反應組件:
import style from "./Button.module.css";
import Link from "next/link";
export const Button: React.FunctionComponent<
React.DetailedReactHTMLElement<
{
onm ouseEnter?: React.MouseEventHandler<Element> | undefined;
onClick?: React.MouseEventHandler;
href?: string | undefined;
ref?: any;
},
HTMLElement
> & {
title?: string;
link?: string;
}
> = ({ title, children, link, ...rest }) => (
<Link href={`${link}`} {...rest}>
{title ?? children}
</Link>
);
當我在某處使用它作為我的 Button 時:
<Button link={exploreLink} title="Explore Event" />
uj5u.com熱心網友回復:
您接受的答案不是Next/link的正確用法。
有幾點需要注意,這樣你就知道發生了什么......
- 您丟失所有 Next/link 屬性(as、shallow、passHref、replace 等)
- 您在下一個/鏈接中缺少所需的錨標記
- 下一個鏈接有自己的型別
link作為道具名稱與標準一樣令人困惑,href并且已經包含在內LinkProps保存所有標準的下一個/鏈接道具;FC是 react 的內置功能組件 - 添加childrenprop 并設定回傳到 JSX/React 節點HTMLProps是 react 內置的合成事件并回應特定的道具HTMLAnchorElement添加所有標準的 html 道具,如 className、title 等。
import NextLink, { LinkProps } from 'next/link';
import { HTMLProps, FC } from 'react';
const LinkButton: FC<LinkProps & HTMLProps<HTMLAnchorElement>> = ({
as, children, href, replace, scroll, shallow, passHref, ...rest
}) => (
<NextLink
as={as}
href={href}
passHref={passHref}
replace={replace}
scroll={scroll}
shallow={shallow}
>
<a {...rest}>
{children}
</a>
</NextLink>
);
如果您添加自定義道具,您可以制作自己的型別
type MyLink = {
customProp?: string;
} & LinkProps & HTMLProps<HTMLAnchorElement>;
LinkButton: FC<MyLink> = ()...
用法
<LinkButton href={exploreLink} title="Explore Event" />
uj5u.com熱心網友回復:
你不需要 React.DetailedReactHTMLElement;嘗試:
React.FunctionComponent<
{
onm ouseEnter?: React.MouseEventHandler<Element>;
onClick?: React.MouseEventHandler;
href?: string;
ref?: any;
}
& {
title?: string;
link?: string;
}
>
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/349973.html
下一篇:展平嵌套物件打字稿
