• [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>
  • 相关阅读:
    .Net WebClient 上传文件错误集锦
    Asp.net 1.1 Treeview 控件的绑定
    SQL Server 2008使用问题集锦
    14 个经典的javascript代码
    C#3.0之自动属性&对象初始化器
    Asp.Net Ajax 2.0 调用WebService 中的方法
    Access Insert Into 语法错误 集锦(不断更新中...)
    项目中常用的几个JS
    广州火车站网上订票系统2011年春运订票指南
    好文收集
  • 原文地址:https://www.cnblogs.com/Answer1215/p/13548037.html
Copyright © 2020-2023  润新知