简体   繁体   English

样式组件 - 两个不同的元素具有相同的 styles

[英]Styled Components - two different elements with the same styles

I have a Button component (in React) which can either be a button or an a element, depending on if a href prop is passed to the component.我有一个Button组件(在 React 中),它可以a button或元素,具体取决于是否将href属性传递给组件。 Something similar to below:类似于以下内容:

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

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

I previously used Sass to style these components, but am now attempting to move over to styled-components .我以前使用 Sass 来设置这些组件的样式,但现在我正试图转移到styled-components However, I have come across an issue where these two elements require the same styles, but the syntax of styled-components would require me to create to separate variables - styled.button and styled.a , with duplicated styles for each.但是,我遇到了一个问题,这两个元素需要相同的 styles,但styled-components的语法需要我创建以分隔变量 - styled.buttonstyled.a ,每个元素都有重复的 styles。

I was wondering if there was a way of dynamically changing the element used in styled-components , maybe based on props in the same way one can change individual CSS properties?我想知道是否有一种方法可以动态更改styled-components中使用的元素,也许基于道具,就像可以更改单个 CSS 属性一样? I have attempted something along the lines of:我尝试了一些类似的东西:

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

but no luck so far.但到目前为止还没有运气。 Any advice would be greatly appreciated.任何建议将不胜感激。

Create generic styles that you can reuse创建可以重复使用的通用 styles

You can extract and pass styles as string args to a styled component.您可以提取 styles 作为字符串参数并将其传递给样式化组件。

const buttonStyles = `
color: red;
...
`

const StyledA = styled.a(buttonStyles);
const StyledButton = styled.button(buttonStyles);

If you need some exceptions如果你需要一些例外

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*/
`;

I tried Joe Lloyd's answer but it didn't work because the function styled.xxx() takes one parameter of type templateStringsArray instead of template String :我尝试了 Joe Lloyd 的回答,但它没有用,因为 function styled.xxx()采用templateStringsArray类型的参数而不是template String

const buttonStyles = [
`
color: red;
...
`
]

const StyledA = styled.a(buttonStyles);
const StyledButton = styled.button(buttonStyles);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM