【发布时间】:2021-05-02 18:22:31
【问题描述】:
这里是forwardedAs 道具上的文档:https://styled-components.com/docs/api#forwardedas-prop。
如你所见,它不是很详细,也没有展示如何正确使用这个道具。
我的问题是:如何访问通过forwardedAs 发送的道具?如何为这些 forwardedAs 属性定义类型?
我可以通过 ...rest 参数访问 forwardedAs 道具,但我需要为这些道具定义类型,因为我也在使用带有 Typescript 的样式组件。
这是我的代码示例:
// Button.jsx
const myPropsToForward = {
href: 'https://somewebsite.com',
// ...more props
}
const Button = styled.button`
// ...button styles
`
const myComponent = () => (
<Button
as={Link}
to={ctaLink}
forwardedAs={myPropsToForward}
/>
)
// Link.jsx
const Link = ({
forwardedAs,
...rest
}) => {
// How do I access the forwardedAs prop from <Button /> here?
return (
<a href={forwardAs?.href} {...rest} />
)
}
在这里,我需要能够访问通过forwardedAs 属性发送的Link 组件中的道具,但是没有关于如何做到这一点的文档。如果我可以访问forwardedAs 属性,我就可以为Link 组件定义正确的类型。我不想依赖...rest 参数,因为我无法为其定义类型。
提前谢谢你。
【问题讨论】:
-
还有一个额外的问题,我将如何在 Link 组件上定义这个 forwardedAs 道具的类型?
标签: javascript reactjs typescript styled-components react-props