如何使用 Next.Js“Link”元素作为 Typescript 的自定义 React 组件

Ali*_*ndy 6 typescript reactjs next.js

我尝试使用“Link”元素作为我的自定义反应组件,我用打字稿修改了它以添加更多设施,但每次在我的项目中使用它时,它都会让我编写一个名为 props 的属性,其中包含一些其他内容特性 :

下面一行是我的打字稿运行时错误:

Type '{ link: string; title: string; }' is missing the following properties from type 'DetailedReactHTMLElement<{ onMouseEnter?: MouseEventHandler<Element> | undefined; onClick?: MouseEventHandler<Element> | undefined; href?: string | undefined; ref?: any; }, HTMLElement>': type, ref, props, keyts(2739)
Run Code Online (Sandbox Code Playgroud)

我编写了自定义反应组件:

import style from "./Button.module.css";
import Link from "next/link";
export const Button: React.FunctionComponent<
  React.DetailedReactHTMLElement<
    {
      onMouseEnter?: React.MouseEventHandler<Element> | undefined;
      onClick?: React.MouseEventHandler;
      href?: string | undefined;
      ref?: any;
    },
    HTMLElement
  > & {
    title?: string;
    link?: string;
  }
  > = ({ title, children, link, ...rest }) => (
  <Link href={`${link}`} {...rest}>
    {title ?? children}
  </Link>
  );
Run Code Online (Sandbox Code Playgroud)

当我在某处使用它作为我的 Button 时:

<Button link={exploreLink} title="Explore Event" />
Run Code Online (Sandbox Code Playgroud)

Sea*_*n W 7

有几点需要注意,这样你就知道发生了什么......

  • 您丢失了所有下一个/链接属性(asshallowpassHrefreplace等)
  • 您缺少next/link 内所需的锚标记
  • 下一个链接有自己的类型 -LinkProps
  • link因为道具名称与标准一样令人困惑href并且它已经包含在内
  • LinkProps持有所有标准的 next/link 属性;
  • FC是 React 的内置功能组件 - 添加childrenprop 并将返回值设置为ReactElement|null
  • HTMLPropsReact 内置了合成事件和 React 特定道具
  • HTMLAnchorElement添加所有标准 html 属性,例如classNametitle等。
import NextLink, { LinkProps } from 'next/link';
import { HTMLProps, FC } from 'react';

const LinkButton: FC<LinkProps & HTMLProps<HTMLAnchorElement>> = ({
  as, children, href, replace, scroll, shallow, passHref, ...rest
}) => (
  <NextLink
    as={as}
    href={href}
    passHref={passHref}
    replace={replace}
    scroll={scroll}
    shallow={shallow}
  >
    <a {...rest}>
      {children}
    </a>
  </NextLink>
);
Run Code Online (Sandbox Code Playgroud)

如果您添加自定义道具,您可以制作自己的类型

import { MouseEvent, HTMLProps, FC } from 'react';

type MyLink = {
 customProp?: string;
} & LinkProps & HTMLProps<HTMLAnchorElement>;

LinkButton: FC<MyLink> = ({ onClick, ...rest }) => {
 const customClick = (event: MouseEvent<HTMLAnchorElement>)={
 }
 ....
}
Run Code Online (Sandbox Code Playgroud)

用法

<LinkButton href={exploreLink} title="Explore Event" />
Run Code Online (Sandbox Code Playgroud)