Multiple Props Options for Styled Components

前端 未结 5 1583
死守一世寂寞
死守一世寂寞 2021-02-06 11:55

I have a navbar component that I have created using Styled Components. I would like to create some props that change the background-color and/or text color.

For instanc

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-06 12:26

    Keep the passed in prop name the same. Then you can utilize a switch/case statement. For example, passing in a color prop and using it as a type to be matched against a case.

    Working example:


    For example:

    
    

    components/Button

    import styled from "styled-components";
    
    const handleColorType = color => {
      switch (color) {
        case "primary":
          return "#03a9f3";
        case "danger":
          return "#f56342";
        default:
          return "#fff";
      }
    };
    
    const Button = styled.button`
      display: block;
      cursor: pointer;
      border: 0;
      margin: 5px 0;
      background: #000;
      font-size: 20px;
      color: ${({ color }) => handleColorType(color)};
    
      &:focus {
        outline: 0;
      }
    `;
    
    export default Button;
    

    If you have multiple attributes (like a color and a background pair), then utilizing the same concept as above, alter the handleColorType to return a string with attributes and invoke the handleColorType function without a style property.

    For example:

    Example
    

    components/MultiButton

    import styled from "styled-components";
    
    const handleColorType = color => {
      switch (color) {
        case "primary":
          return "color: #03a9f3; background: #000;";
        case "danger":
          return "color: #fff; background: #f56342;";
        default:
          return "color: #000; background: #eee;";
      }
    };
    
    const MultiButton = styled.button`
      display: block;
      margin: 5px 0;
      cursor: pointer;
      border: 0;
      font-size: 20px;
      ${({ color }) => handleColorType(color)};
    
      &:focus {
        outline: 0;
      }
    `;
    
    export default MultiButton;
    

提交回复
热议问题