[英]how to make a Next.js "Link" 's "href" property optional
我已經將 Next.js 鏈接作為自定義 React function 和 typescript,因為“鏈接”需要“href”屬性才能在我想要的任何地方調用它。 所以我不能將它用作 forms 中用作提交按鈕的按鈕
import NextLink, { LinkProps } from "next/link";
import { HTMLProps, FC } from "react";
export const LinkButton: FC<LinkProps & HTMLProps<HTMLAnchorElement>> = ({
as,
children,
href,
replace,
scroll,
shallow,
passHref,
className,
title,
onClick,
...rest
}) => (
<NextLink
as={as}
href={href}
passHref={passHref}
replace={replace}
scroll={scroll}
shallow={shallow}
>
<a className={className} {...rest}>
{children || title}
</a>
</NextLink>
);
當我在某個地方使用它時,它給了我這個錯誤
<LinkButton onClick={() => alert("hello")} title="Find Events" />
Property 'href' is missing in type '{ onClick: () => void; title: string; }' but required in
type 'LinkProps'.
我怎么能讓 href 可選然后如果它沒有被調用我可以有條件地添加一個“”標簽除了“”標簽
您可以省略href
屬性並定義為可選:
Omit<LinkProps & HTMLProps<HTMLAnchorElement>, "href"> & { href?: string }
然后在組件道具解構中您需要指定默認值
...
href = "",
...
為了使 href 永遠不會為空,您可以獲取它的路由並在未定義時返回它
const router = useRouter()
<NextLink
as={as}
href={href ? href : router.asPath} // <---
passHref={passHref}
replace={replace}
scroll={scroll}
shallow={shallow}
>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.