javascript - 如何使 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 可选然后如果它没有被调用我可以有条件地添加一个“”标签除了“”标签
解决方案
您可以省略href
属性并定义为可选:
Omit<LinkProps & HTMLProps<HTMLAnchorElement>, "href"> & { href?: string }
然后在组件道具解构中您需要指定默认值
...
href = "",
...
推荐阅读
- javascript - 使用 LocalStorage API 持久化 Miragejs 数据库
- python - 如何将excel文件的名称作为参数传递给函数
- html - 我有选择框,如何在选择框的项目上添加徽标?
- python - 删除 matplotlib seaborn 点图中的垂直线
- javascript - 将 typescript 项目与托管在本地 Apache 服务器上的现有 PHP 应用程序集成和调试
- ansible - 为剧本设置 Ansible 环境
- arrays - 出现错误“无法将'listItem'类型的值转换为预期的参数类型'String?'”
- python - ModuleNotFoundError:没有名为“pyarrow._dataset”的模块
- sorting - 根据Google Sheets中选择主题的组合查询数据
- python - 如何让 svgwrite.drawing() 对象在每次迭代时重新初始化?