我有一个样式设置的按钮:
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; }'.
答案 0 :(得分:0)
TypeScript抱怨是因为来自Link
的{{1}}组件要求您指定一个react-router
道具。我不确定您要实现的目标,但是to
应该已经呈现为Link
标签。
如果您愿意提供指向外部网站的链接,那么您可能不想使用<a />
,而要使用styled(Link)
。
如果您担心同时为styled.a
和styled(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;
`