如何在TypeScript自定义Next.js Link组件中将href属性设为可选
解决方案
你遇到的报错本质是因为组件直接继承了Next.js原生LinkProps的必填href约束,同时原有逻辑只支持渲染a标签。按下方修改即可实现你要的效果:
import NextLink, { LinkProps } from "next/link"; import { HTMLProps, FC } from "react"; // 调整Props类型:移除原生href必填约束,同时兼容a、button标签的原生属性 type LinkButtonProps = (Omit<LinkProps, "href"> & { href?: string; } & HTMLProps<HTMLAnchorElement>) | HTMLProps<HTMLButtonElement>; export const LinkButton: FC<LinkButtonProps> = (props) => { // 存在有效href时走跳转链接逻辑 if ("href" in props && props.href) { const { as, children, href, replace, scroll, shallow, passHref, className, title, onClick, ...rest } = props; return ( <NextLink as={as} href={href} passHref={passHref} replace={replace} scroll={scroll} shallow={shallow} > <a className={className} onClick={onClick} {...rest}> {children || title} </a> </NextLink> ); } // 无href时走普通button逻辑,默认type为button避免表单中误触发提交 const { className, title, children, onClick, type = "button", ...rest } = props; return ( <button type={type} className={className} onClick={onClick} {...rest}> {children || title} </button> ); };
使用示例
修改后你原来的调用方式可以正常运行,同时支持多种场景:
// 渲染为普通按钮 <LinkButton onClick={() => alert("hello")} title="Find Events" /> // 渲染为跳转链接 <LinkButton href="/events" title="Find Events" /> // 渲染为表单提交按钮 <LinkButton type="submit" title="提交表单" />
内容的提问来源于stack exchange,提问作者user16911633
相关产品推荐
相关产品推荐

