forwardedAs
The forwardedAs
prop is not for passing down props. It's actually for passing down an as
prop to the next item in the chain. Consider this example:
const Button = styled.button`
padding: 20px;
`;
const Link = (props: any) => { // not properly typed
return <Button {...props} />;
};
const MyLink = styled(Link)`
background-color: blue;
`
const MyComponent = () => (
<MyLink forwardedAs={"div"}>
Text
</MyLink>
);
We have a Button
which is a styled component and we have a MyLink
which is another styled component that passes its props down to the Button
. If we want to set the as
prop on the Button
, we can set forwardedAs
on MyLink
.
With <MyLink forwardedAs={"div"}>
, the element that we ultimately render to the DOM is a div
rather than a button
and it applies the styles from both styled
HOCs.
Passing Props
Based on your example here, the Link
component is not actually needed. You can set as="a"
on your Button
to render it as a link and pass through myPropsToForward
directly.
const myPropsToForward = {
href: "https://somewebsite.com"
// ...more props
};
const Button = styled.button`
background: yellow;
padding: 20px;
`;
const MyComponent = () => (
<Button as="a" {...myPropsToForward}>
Text
</Button>
);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…