简体   繁体   中英

Multiple Prop Checks in Styled Components

I know that in styled-components, I can do a check for a prop like this:

${props => { if (props.size)...return...

However, from what I can tell if I want to do a second prop check, then I need to start all over again:

${props => { if (props.color)...return...

What I am wondering is if there is a way to do just one ${props... with different returns for different cases?

If so, any idea how?

Thanks.

You can simplify a little by accessing the props object up front. There's a little less repetition this way.

const StyledComponent = styled.div(
  (props) => `
    background-color: green;

    ${props.warn && `
      background-color: yellow;
    `}

    ${props.alert && `
      background-color: red;
    `}

  `
);

有一个叫做styled-is的包,它可以帮助你以一种干净和漂亮的方式做到这一点。

I prefer to keep my css separate, like in a styles.js file. Take the following code for example. It keeps the css organized, and makes implementing the different options pretty clean. Of course, add your css into the appropriate definitions

//styles.js
import { css } from 'styled-components';

export const buttonbase = css`/*base styles for all buttons*/`;
export const small = css`/*small size styles*/`;
export const medium = css`/*default size styles*/`;
export const large = css`/*large size styles*/`;
export const floating = css`/*float styles*/`;

And in your component file:

//Button.js
import React from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';
import * as Styles from './styles';

const propTypes = {
  floating: PropTypes.bool,
  size: PropTypes.oneOf(['small', 'medium', 'large']),
  children: PropTypes.node,
};

const defaultProps = {
  floating: false,
  size: 'medium',
};

const ButtonBase = styled.button`
  ${Styles.buttonbase};
  ${props => (props.floating ? Styles.floating : '')};
  ${props => Styles[props.size]};
`;

const Button = ({ floating, size, children, ...rest }) => (
  <ButtonBase
    size={size}
    floating={floating}
    {...rest}
  >
    {children}
  </ButtonBase>
);

Button.propTypes = propTypes;
Button.defaultProps = defaultProps;

export default Button;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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