首页 > 解决方案 > 如何使 Next.js "Link" 的 "href" 属性可选

问题描述

我已经将 Next.js 链接作为带有 typescript 的自定义 React 函数,因为“链接”需要“href”属性才能在我想要的任何地方调用它。所以我不能将它用作表单中的提交按钮

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 可选然后如果它没有被调用我可以有条件地添加一个“”标签除了“”标签

标签: javascriptreactjstypescriptnext.js

解决方案


您可以省略href属性并定义为可选:

Omit<LinkProps & HTMLProps<HTMLAnchorElement>, "href"> & { href?: string }

然后在组件道具解构中您需要指定默认值

...
href = "",
...

推荐阅读