使用带有打字稿的样式化组件 "as" prop

Using styled components "as" prop with typescript

我目前正在构建一个模式库,其中我使用 Reactstyled-components 构建了一个 Button 组件。 基于 Button 组件,我希望我所有的 Links 组件看起来完全一样,并接收完全相同的道具。 为此,我使用了 styled-components 中的 as 道具,它允许我将已经构建的元素用作另一个标签或组件。

按钮组件

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',
}

Link 组件

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

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'.

...这是有道理的,因为按钮没有 react-router-dom.

中的 Link 组件所需的道具 to

你将如何处理这样的事情?当使用 Button 时,to 道具甚至不应该在类型中,而当使用 Link 时,应该需要 to

使用

<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