zoukankan      html  css  js  c++  java
  • [React] Use react styled system with styled components

    In this lesson we’ll improve a generic button primitive component by refactoring it with Styled System to simplify the implementation.

    The naïve styled-component implementation has styles like this:

    import styled from 'styled-components'
    
    export const Button = styled.button`
       ${(props) => (props.fullWidth ? '100%' : undefined)};
      padding: 8px 16px;
      background-color: ${(props) =>
        props.variant === 'primary'
          ? props.theme.colors.primary
          : props.theme.colors.secondary};
      color: snow;
      border: 0;
      border-radius: 0.2rem;
      font-size: 1rem;
      cursor: pointer;
    
      &:hover,
      &:active {
        background-color: ${(props) => props.theme.colors.accent};
      }
    
      &:focus {
        outline: 0;
        box-shadow: 0 0 0 2px white, 0 0 0 4px salmon;
      }
    
      @media (max- 550px) {
         100%;
      }
    `
    Button.propTypes = {
      variant: PropTypes.oneOf(['secondary', 'primary']),
    }
    Button.defaultProps = {
      variant: 'secondary',
    }

    Convert to Style system:

    import styled, { ThemeProvider } from 'styled-components'
    import css from '@styled-system/css'
    import { variant, space } from 'styled-system'
    
    const variants = {
      primary: {
        color: 'background',
        backgroundColor: 'primary',
      },
      secondary: {
        color: 'primary',
        backgroundColor: 'background',
      },
    }
    
    const Button = styled.button(
      css({
        boxSizing: 'border-box',
        display: 'inline-block',
        textAlign: 'center',
        px: 4,
        py: 3,
        color: (props) => (props.variant === 'primary' ? 'background' : 'primary'),
        backgroundColor: (props) =>
          props.variant === 'primary' ? 'primary' : 'background',
        border: '1px solid',
        borderColor: 'primary',
        borderRadius: 'round',
        fontFamily: 'body',
        fontSize: 'm',
        textDecoration: 'none',
    
        '&:hover:not(:disabled),&:active:not(:disabled),&:focus': {
          outline: 0,
          color: 'background',
          borderColor: 'accent',
          backgroundColor: 'accent',
          cursor: 'pointer',
        },
    
        '&:disabled': {
          opacity: 0.6,
          filter: 'saturate(60%)',
        },
      }),
      variant({ variants }),
      space,
    )
    
    export default Button

    Use:

            <Button p="10 20" fullWidth variant="primary">
              Click Me
            </Button>
  • 相关阅读:
    MySQL数据库的主从同步
    学习Java必看的Java书籍(高清中文最新版附下载链接)
    servlet重点知识总结
    JUnit & JMockit单元测试
    mongodb重点知识总结
    Quartz学习总结
    IDEA使用总结
    bat脚本知识总结
    linux shell脚本相关知识
    SpringMVC重点知识总结
  • 原文地址:https://www.cnblogs.com/Answer1215/p/13548037.html
Copyright © 2011-2022 走看看