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)
有几点需要注意,这样你就知道发生了什么......
as、
shallow、passHref、replace等)LinkPropslink因为道具名称与标准一样令人困惑href并且它已经包含在内LinkProps持有所有标准的 next/link 属性;FC是 React 的内置功能组件 - 添加childrenprop 并将返回值设置为ReactElement|nullHTMLPropsReact 内置了合成事件和 React 特定道具HTMLAnchorElement添加所有标准 html 属性,例如className、title等。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)
| 归档时间: |
|
| 查看次数: |
11329 次 |
| 最近记录: |