gpt4 book ai didi

javascript - 使用带有 typescript 的样式化组件 "as" Prop

转载 作者:可可西里 更新时间:2023-11-01 02:47:50 26 4
gpt4 key购买 nike

我目前正在构建一个模式库,我在其中构建了一个 Button组件使用 Reactstyled-components .基于Button组件,我想要我所有的 Link s 组件看起来完全一样,并接收完全相同的 Prop 。为此,我使用 as Prop 来自 styled-components ,这让我可以将已构建的元素用作另一个标签或组件。

按钮组件

import * as React from 'react'
import { ButtonBorderAnimation } from './ButtonAnimation'
import { ButtonProps, ButtonVariant } from './Button.types'
import { ButtonBase, LeftIcon, RightIcon } from './Button.styled'

function Button({
variant = ButtonVariant.Filled,
children,
leftIcon = null,
rightIcon = null,
...props
}: ButtonProps): JSX.Element {
return (
<ButtonBase variant={variant} {...props}>
{variant !== ButtonVariant.Ghost ? (
<ButtonBorderAnimation {...props} />
) : null}
{leftIcon ? <LeftIcon>{leftIcon}</LeftIcon> : null}
{children}
{rightIcon ? <RightIcon>{rightIcon}</RightIcon> : null}
</ButtonBase>
)
}

export default Button

按钮类型

export interface ButtonProps {
children: React.ReactNode
variant?: 'filled' | 'outlined' | 'ghost'
size?: 'small' | 'regular'
underlinedOnHover?: boolean
leftIcon?: React.ReactNode
rightIcon?: React.ReactNode
inverse?: boolean
}

export enum ButtonVariant {
Filled = 'filled',
Outlined = 'outlined',
Ghost = 'ghost',
}

export enum ButtonSize {
Small = 'small',
Regular = 'regular',
}

链接组件

import * as React from 'react'
import Button from '../Button/Button'
import { Link as LinkRouter } from 'react-router-dom'
import { LinkProps } from './Link.types'

function Link({ to, ...props }: LinkProps): JSX.Element {
return <Button to={to} as={LinkRouter} {...props} />
}

export default Link

链接类型

import { ButtonProps } from '../Button/Button.types'
import { LinkProps } from 'react-router-dom'

type RouterLinkWithButtonProps = ButtonProps & LinkProps

export interface LinkProps extends RouterLinkWithButtonProps {}

当我执行上述操作时,这个问题就来了......

Property 'to' does not exist on type 'IntrinsicAttributes & ButtonProps'.

...这是有道理的,因为按钮没有属性 to这是 Link 所必需的来自 react-router-dom 的组件.

你将如何处理这样的事情?在何处使用 Button to prop 甚至不应该在类型中,并且在使用 Linkto应该是必需的。

使用

<Button>Hello</Button>
<Link to="/somewhere">Hello</Link>

最佳答案

这应该有效。

function Link(_props: LinkProps): JSX.Element {
const props = { as: LinkRouter, ..._props };
return <Button {...props} />
}

请注意,TypeScript 适用于 strict object literal assignment checks这可以通过预先将对象文字分配给变量而不是直接将其作为函数参数传递来放宽,这与 React 组件 props 分配行为一致。

declare function foo(arg: { a: number }): void;

foo({ to: '', a: 1 }); // error

const arg = { to: '', a: 1 };
foo(arg); // no error

关于javascript - 使用带有 typescript 的样式化组件 "as" Prop ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56837759/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com