首页 > 解决方案 > 如何在 react 和 typescript 中使用样式化组件重构代码?

问题描述

我想使用 react 和 typescript 重构样式组件的代码。

我有两个黑色和蓝色链接共享相同的 css,但有些风格不同。

下面是代码,

return (
    <Wrapper>
        <ButtonLink a="someurl">
            black
        </ButtonLink>
        <ButtonLink a="url">
            blue
        </ButtonLink>
    </Wrapper>
);


const ButtonLink = styled.a`
    border: none;
    background: none;
    display: flex;
    justify-content: center;
    align-items: center;
`;

现在对于黑色链接,我想添加背景颜色:黑色,对于蓝色链接,我想添加背景颜色蓝色。

如何使用样式组件将这些样式添加到这两个链接中。有人可以帮我解决这个问题。谢谢。

标签: reactjstypescript

解决方案


例如,您需要将属性作为道具传递给组件

<ButtonLink color="red" href="#">Red</ButtonLink>
const ButtonLink = styled.a`
  ...,
  color: ${props => props.color}
`

推荐阅读