【问题标题】:How to refactor code using styled components in react and typescript?如何在 react 和 typescript 中使用样式化组件重构代码?
【发布时间】:2020-11-10 16:27:49
【问题描述】:

我想使用 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;
`;

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

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

【问题讨论】:

  • 您必须将颜色作为道具传递给 ButtonLink 样式的组件,然后有条件地更改背景颜色
  • @someuser2491 感谢validate我的回答。也请upvote所有有用的答案吗?

标签: reactjs typescript


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    您可以在样式化组件中使用道具

    const ButtonLink = styled.a`
        border: none;
        background: ${props => props.bgColor};
        display: flex;
        justify-content: center;
        align-items: center;`
    

    然后像这样传入props

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

    或者,如果您不想传递道具,您可以扩展初始 ButtonLink 组件

    const ButtonLink = styled.a`
        border: none;
        display: flex;
        justify-content: center;
        align-items: center;`
    
    
    const BlueButtonLink = styled(ButtonLink)`
        background-color: #0000FF;`
    
    const BlackButtonLink = styled(ButtonLink)`
        background-color: #000;`
    
    
    return (
      <Wrapper>
         <BlackButtonLink a="someurl">
             black
         </BlackButtonLink>
         <BlueButtonLink a="url" >
             blue
         </BlueButtonLink>
      </Wrapper>
    );
    

    【讨论】:

      【解决方案3】:

      只需将颜色添加为ButtonLink 组件的道具即可。但是不要忘记为它添加接口,因为您使用的是 TypeScript:

      return (
          <Wrapper>
              <ButtonLink color="black" a="someurl">
                  black
              </ButtonLink>
              <ButtonLink color="blue" a="url">
                  blue
              </ButtonLink>
          </Wrapper>
      );
      
      interface ButtonLinkProps {
          color: string
      }  
      
      const ButtonLink = styled.a<ButtonLinkProps>`
          color: ${props => props.color}
          border: none;
          background: none;
          display: flex;
          justify-content: center;
          align-items: center;
      `;
      

      【讨论】:

        猜你喜欢
        • 2021-04-13
        • 2020-06-03
        • 2021-01-13
        • 2021-08-03
        • 2019-01-14
        • 2020-11-05
        • 1970-01-01
        • 2021-10-07
        • 2021-11-01
        相关资源
        最近更新 更多