Koc*_*r4d 5 typescript definitelytyped styled-components
我有一个样式按钮:
import { Link } from 'react-router-dom'
import styled from 'styled-components'
const Button = styled(Link)`
display: block;
border: 1px solid white;
padding: 5px;
`
Run Code Online (Sandbox Code Playgroud)
我可以将它用作Link:
<Button to='/' />
Run Code Online (Sandbox Code Playgroud)
但有时我想将其用作a:
<Button as='a' href='/' />
Run Code Online (Sandbox Code Playgroud)
但在第二种情况下,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; }'.
Run Code Online (Sandbox Code Playgroud)
小智 2
TypeScript 正在抱怨,因为Link来自的组件react-router要求您指定一个toprop。我不确定您想要实现什么,但Link应该已经呈现为<a />标签。
如果您愿意呈现指向外部网站的链接,那么您可能不想使用styled(Link),而是使用styled.a.
如果您担心 和 重复您的样式styled(Link),styled.a您可能需要使用css 辅助函数编写可重用的按钮样式编写可重用的按钮样式,并将其包含在两个样式组件中。
不幸的是,我相信这是目前唯一的选择,因为我也遇到过类似的情况,并尝试as={Link}在 a 上使用styled.a,并且 TypeScript 抱怨无法识别的道具。我相信 TypeScript 上的多态属性的实现as并不完全有效,因此稍后可能会有修复。
| 归档时间: |
|
| 查看次数: |
2835 次 |
| 最近记录: |