【问题标题】:Styled Components - two different elements with the same styles样式组件 - 具有相同样式的两个不同元素
【发布时间】:2020-08-14 13:31:55
【问题描述】:

我有一个 Button 组件(在 React 中),它可以是 buttona 元素,具体取决于是否将 href 属性传递给组件。类似于以下内容:

const Button = ({ children, href, onClick }) => {
    if(href) {
        return <a href={href} onClick={onClick}>{children}</a>;
    }

    return <button type="button" onClick={onClick}>{children}</button>;
};

我之前使用 Sass 来设置这些组件的样式,但现在我尝试转移到 styled-components。但是,我遇到了一个问题,这两个元素需要相同的样式,但 styled-components 的语法要求我创建分隔变量 - styled.buttonstyled.a,每个变量都有重复的样式。

我想知道是否有一种方法可以动态更改styled-components 中使用的元素,也许基于道具,就像可以更改单个 CSS 属性一样?我尝试过类似的东西:

const StyledButton = styled((props) => props.href ? 'a' : 'button')`
    ...
`;

但到目前为止还没有运气。任何建议将不胜感激。

【问题讨论】:

    标签: javascript reactjs styled-components


    【解决方案1】:

    我尝试了 Joe Lloyd 的回答,但没有成功,因为函数 styled.xxx() 采用 templateStringsArray 类型的一个参数而不是 template String

    const buttonStyles = [
    `
    color: red;
    ...
    `
    ]
    
    const StyledA = styled.a(buttonStyles);
    const StyledButton = styled.button(buttonStyles);
    

    【讨论】:

      【解决方案2】:

      创建可以重复使用的通用样式

      您可以提取样式并将其作为字符串参数传递给样式化组件。

      const buttonStyles = `
      color: red;
      ...
      `
      
      const StyledA = styled.a(buttonStyles);
      const StyledButton = styled.button(buttonStyles);
      

      如果您需要一些例外情况

      import styled, { css } from ‘styled-components’;
      
      const baseInputStyles = css`
        padding: 0.5em;
      `;
      
      const StyledA = styled.a`
        ${baseInputStyles}
      `;
      
      const StyledButton = styled.button`
        ${baseInputStyles}
        /* make changes as needed*/
      `;
      

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-13
      • 1970-01-01
      • 1970-01-01
      • 2019-04-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多