简体   繁体   English

React Styled-Components 3 按钮大小

[英]React Styled-Components 3 Button sizes

What is the best way have 3 style types based on props?基于道具的 3 种样式类型的最佳方式是什么?

Like Bootstrap, aiming to have a default, small, and medium size.和 Bootstrap 一样,目标是有一个默认的、小号和中号。

Here I have default and small, but how do I account for a large size too?这里我有默认和小,但是我怎么也考虑大尺寸呢?

 const Button = styled.button`
   background: teal;
   border-radius: 8px;
   color: white;
   height: ${props => props.small ? 40 : 60}px;
   width: ${props => props.small ? 60 : 120}px;
`;

class Application extends React.Component {
  render() {
    return (
      <div>
        <Button small>Click Me</Button>
        <Button>Click Me</Button>
        <Button large>Click Me</Button>
      </div>
    )
  }
}

Codepen密码笔

Here's an abbreviated example of an option that I use.这是我使用的一个选项的缩写示例。

/* import separate css file from styles.js */
import * as Styles from './styles';

/* concat styles based on props */
const ButtonBase = styled.button`
  ${Styles.buttonbase};
  ${props => Styles[props.size]};
  ${props => Styles[props.variant]};
`;

const Button = ({ size, variant, ...rest }) => (
  <ButtonBase
    size={size}
    variant={variant}
    {...rest}
    ...

And in the styles file (with the css removed for brevity)在样式文件中(为简洁起见,删除了 css)

import { css } from 'styled-components';

/* styles common to all buttons */
export const buttonbase = css`...`;

/* theme variants */
export const primary = css`...`;
export const secondary = css`...`;
export const tertiary = css`...`;

/* size variants */
export const small = css`...`;
export const medium = css`...`;
export const large = css`...`;

I've seen this as a solution too:我也将其视为解决方案:

const ButtonBase = styled.button`
    padding: ${props => {
        if (props.xl) return props.theme.buttonSize.xl;
        if (props.lg) return props.theme.buttonSize.lg;
        if (props.md) return props.theme.buttonSize.md;
        if (props.sm) return props.theme.buttonSize.sm;
        return props.theme.buttonSize.nm;
    }};
`

https://codesandbox.io/s/735ppo790x https://codesandbox.io/s/735ppo790x

Harsha Venkatram, here is the typescript version: Harsha Venkatram,这是打字稿版本:

import * as Styles from './styles';

interface Props {
  size: number; //for example, or string or whatever type is it
  variant: 'primary' | 'secondary' | 'tertiary' //etc...
}

const ButtonBase = styled.button<Props>`
  ${Styles.buttonbase};
  ${props => Styles[props.size]};
  ${props => Styles[props.variant]};
`;

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

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