如何在样式组件中使用"as"函数



我正在尝试使用样式化组件对链接进行样式化。根据道具的不同,它将显示<button><Link>。我看到我可以使用函数as,但当我这样做时,它不会在生成的链接中显示href。有人有解决方案吗?

const Button = styled.button`
...styles
`;

<Button href={props.url} as={props.url ? Link : "button"}>
{props.children}
</Button>
<Button>Button without url</Button>
<Button url="/">Button with url</Button>

谢谢!

这就是您可以做的:

如果url不在那里,它将保留为按钮else锚标签

<Button href={props.url || # } as={props.url && "a" }>
{props.children}
</Button>

我建议您使用它来实现您想要的。你可以简单地写下:

<Box as={props.url? Link : Button} to={props.url}>About</Box>

感谢您的回答,我做了这个解决方案,现在它可以工作了:

<Container as={props.url && Link} to={props.url} href={props.ext && props.url}>
{props.children}
</Container>

最新更新