使用TypeScript和样式化组件as作为道具

时间:2018-11-09 16:52:06

标签: typescript styled-components definitelytyped

我有一个样式设置的按钮:

import { Link } from 'react-router-dom'
import styled from 'styled-components'

const Button = styled(Link)`
  display: block;
  border: 1px solid white;
  padding: 5px; 
`

我可以将其用作Link

<Button to='/' />

但有时我想将其用作a

<Button as='a' href='/' />

但是在第二种情况下,TypeScript抱怨:

Type '{ children: string; as: string; href: string; }' is not assignable to type 'Readonly<ThemedOuterStyledProps<WithOptionalTheme<LinkProps, any>, any>>'.
Property 'to' is missing in type '{ children: string; as: string; href: string; }'.

"as" polymorphic prop

3 个答案:

答案 0 :(得分:0)

TypeScript抱怨是因为来自Link的{​​{1}}组件要求您指定一个react-router道具。我不确定您要实现的目标,但是to应该已经呈现为Link标签。

如果您愿意提供指向外部网站的链接,那么您可能不想使用<a />,而要使用styled(Link)

如果您担心同时为styled.astyled(Link)重复样式,则可能要使用css helper function编写可重复使用的按钮样式,并将其包含在两个样式中样式的组件。

不幸的是,我认为这是目前唯一的选择,就像我在类似情况下一样,并尝试在styled.a上使用as={Link},而TypeScript抱怨无法识别的道具。我相信在TypeScript上实现多态styled.a道具的功能尚不完善,因此以后可能会修复。

答案 1 :(得分:0)

由于此@types/styled-components问题-> link

,它无法正常工作

答案 2 :(得分:0)

解决方案是将缺少的道具显式添加到样式元素中,例如

const Button = styled(Link)<{to: any}>`
  display: block;
  border: 1px solid white;
  padding: 5px; 
`