[英]how to make a Next.js "Link" 's "href" property optional
I've made the Next.js Link as a custom React function with typescript since the "href" property is required for "Link" to be able to call it anywhere I want.我已经将 Next.js 链接作为自定义 React function 和 typescript,因为“链接”需要“href”属性才能在我想要的任何地方调用它。 so I couldn't used it as a button which working as a submit button in forms
所以我不能将它用作 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>
);
and when I used it in somewhere it gave me this error当我在某个地方使用它时,它给了我这个错误
<LinkButton onClick={() => alert("hello")} title="Find Events" />
Property 'href' is missing in type '{ onClick: () => void; title: string; }' but required in
type 'LinkProps'.
how could I make href optional then if it doesn't called I can conditionally add a "" tag except of "" tag我怎么能让 href 可选然后如果它没有被调用我可以有条件地添加一个“”标签除了“”标签
You can omit href
property and define as optional:您可以省略
href
属性并定义为可选:
Omit<LinkProps & HTMLProps<HTMLAnchorElement>, "href"> & { href?: string }
and then inside component props destructuring you need to specify default value然后在组件道具解构中您需要指定默认值
...
href = "",
...
In order that href is never empty you can get its route and return it when it is not defined为了使 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.