[英]Next.js Typescript Project Custom Link Button Proptype
My project has a custom Button
component and a NextLink
wrapper that passes the href
down to the button.我的项目有一个自定义Button
组件和一个NextLink
包装器,它将href
传递给按钮。 I want to combine these two components for cleanliness' sake, but something goes wrong when I combine the props for each.为了清洁起见,我想将这两个组件结合起来,但是当我为每个组件结合道具时出现了问题。 I am unable to spread rest
in the prop destructuring statement.我无法在道具解构语句中传播rest
。 I get a TypeScript error saying:我收到 TypeScript 错误说:
Rest types may only be created from object types.ts(2700) Rest 类型只能从 object types.ts(2700) 创建
Whenever I remove (or comment out) size: 'xs' | 's' | 'm' | 'l' | 'xl'
每当我删除(或注释掉) size: 'xs' | 's' | 'm' | 'l' | 'xl'
size: 'xs' | 's' | 'm' | 'l' | 'xl'
size: 'xs' | 's' | 'm' | 'l' | 'xl'
, the error disappears. size: 'xs' | 's' | 'm' | 'l' | 'xl'
,错误消失。 So my question is obviously, is something wrong with my size
type?所以我的问题很明显,我的size
有问题吗? Is this a bug?这是一个错误吗? Component follows.组件如下。
import NextLink, { LinkProps } from 'next/link'
import { HTMLProps, FC } from 'react'
import { GlobalColorsType } from '../../types'
import Button from './Button'
type ButtonProps = {
type: GlobalColorsType
size: 'xs' | 's' | 'm' | 'l' | 'xl'
onClick: () => void
className?: string
id?: string
style?: any
}
type LinkButtonProps = ButtonProps & LinkProps & HTMLProps<HTMLAnchorElement>
const LinkButton: FC<LinkButtonProps> = ({
as,
children,
href,
replace,
scroll,
shallow,
passHref,
...rest
}) => (
<NextLink
as={as}
href={href}
passHref={passHref}
replace={replace}
scroll={scroll}
shallow={shallow}
>
<a {...rest}>
<Button ...ButtonProps/>
</a>
</NextLink>
)
export default LinkButton
The HTMLProps
type includes all the possible attributes that every HTML element can have. HTMLProps
类型包括每个 HTML 元素可以具有的所有可能属性。 You should use AnchorHTMLAttributes
instead, which provides anchor-specific props, and further narrows down the props type.您应该改用AnchorHTMLAttributes
,它提供特定于锚点的道具,并进一步缩小道具类型。
type LinkButtonProps = ButtonProps & LinkProps & AnchorHTMLAttributes<HTMLAnchorElement>
If the above doesn't cover all the attributes you need for the anchor element, you can use ComponentProps<'anchor'>
instead.如果上面没有涵盖锚元素所需的所有属性,则可以使用ComponentProps<'anchor'>
代替。
type LinkButtonProps = ButtonProps & LinkProps & ComponentProps<'anchor'>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.