Atomic Habits

React. Part2. ch2. 01-2. styled-components 본문

IT/Style(Library)

React. Part2. ch2. 01-2. styled-components

체계성 2021. 11. 10. 23:07

https://styled-components.com/docs/basics#getting-started

 

* styled.tag`` 는 return 이 포함된 func 외부에 생성한다.

 - 내부에 있다면 컴포넌트 라이프사이클에 따라 styled가 계속 생성되어 성능 저하 야기

import React from "react";
import styled from "styled-components";

// Create a Title component that'll render an <h1> tag with some styles
const Title = styled.h1`
  font-size: 1.5em;
  text-align: center;
  color: palevioletred;
`;

// Create a Wrapper component that'll render a <section> tag with some styles
const Wrapper = styled.section`
  padding: 4em;
  background: papayawhip;
`;

const Button = styled.button`
  /* Adapt the colors based on primary prop */
  /* props 에 따라 다른 스타일 적용*/
  background: ${(props) => (props.primary ? "palevioletred" : "white")};
  color: ${(props) => (props.primary ? "white" : "palevioletred")};

  font-size: 1em;
  margin: 1em;
  padding: 0.25em 1em;
  border: 2px solid palevioletred;
  border-radius: 3px;
`;

// styled() 안에 내가 만든 컴포넌트의 스타일을 가져온다.(상속 및 확장)
const TomatoButton = styled(Button)`
  //
  color: tomato;
  border-color: tomato;
`;

// 기존 컴포넌트의 글자 반대로
const ReversedButton = (props) => (
  <Button {...props} children={props.children.split("").reverse()} />
);

export default function StyledCOmponentExample() {
  // Use Title and Wrapper like any other React component – except they're styled!
  return (
    <>
      <Wrapper>
        <Title onClick={() => alert("Title!")}>Hello World!</Title>
      </Wrapper>
      <Button onClick={() => alert("normal!")}>Normal</Button>
      <Button onClick={() => alert("primary!")} primary>
        Primary
      </Button>
      <TomatoButton onClick={() => alert("tomato!")}>Primary</TomatoButton>
      <br />
      <Button as="a" href="#">
        Link with Button styles
      </Button>
      <TomatoButton as="a" href="#">
        {/*  as="a" : a 태그 처럼 작동(밑줄, 클릭 시 # 등) 
            개발자 도구에서는 <a>로 표시됨. div, p 등등 가능  
            as에는 기본 태그만이 아니라 커스텀 컴포넌트도 넣을 수 있다.  
      */}
        Link with Tomato Button styles
      </TomatoButton>
      <Button as={ReversedButton}>
        Custom Button with Normal Button styles
      </Button>
    </>
  );
}

styled-components :  리액트 컴포넌트 생성과 스타일 명시를 함께 한다. 

 

================ 기존 리액트 컴포넌트 방식 ================ 

const Title2 = () => {

return <div>Hello</div>

}

return <Title2>

 

================ styled-compts 방식 ================  

 -> 컴포넌트 생성과 스타일 나열을 함께 하므로, 

     컴포넌트는 지우고, 스타일은 지우지 않아서, 

     css 파일에 스타일이 지속적으로 쌓이면서 복잡하게 얽히는 상황 방지

 

export default function StyledCOmponentExample() {

// Create a Title component that'll render an <h1> tag with some styles

const Title = styled.h1`

font-size: 1.5em;

text-align: center;

color: palevioletred;

`;

 

// Use Title and Wrapper like any other React component – except they're styled!

return (

<Title>Hello World!</Title>

);

 

================ props에 따른 다른 스타일 적용 ================  

import React from "react";
import styled from "styled-components";

export default function StyledCOmponentExample() {
  // Create a Title component that'll render an <h1> tag with some styles
  const Title = styled.h1`
    font-size: 1.5em;
    text-align: center;
    color: palevioletred;
  `;

  // Create a Wrapper component that'll render a <section> tag with some styles
  const Wrapper = styled.section`
    padding: 4em;
    background: papayawhip;
  `;

  const Button = styled.button`
    /* Adapt the colors based on primary prop */
    background: ${(props) => (props.primary ? "palevioletred" : "white")};
    color: ${(props) => (props.primary ? "white" : "palevioletred")};

    font-size: 1em;
    margin: 1em;
    padding: 0.25em 1em;
    border: 2px solid palevioletred;
    border-radius: 3px;
  `;

  // Use Title and Wrapper like any other React component – except they're styled!
  return (
    <>
      <Wrapper>
        <Title>Hello World!</Title>
      </Wrapper>
      <Button>Normal</Button>
      <Button primary>Primary</Button>
    </>
  );
}

 

================ 스타일 상속 가능 ================  

Extending Styles

// The Button from the last section without the interpolations
const Button2 = styled.button`
  color: palevioletred;
  font-size: 1em;
  margin: 1em;
  padding: 0.25em 1em;
  border: 2px solid palevioletred;
  border-radius: 3px;
`;

// A new component based on Button, but with some override styles
const TomatoButton = styled(Button2)`  <--------- 기존 스타일 컴포넌트 상속
  color: tomato;
  border-color: tomato;
`;

render(
  <div>
    <Button2>Normal Button</Button2>
    <TomatoButton>Tomato Button</TomatoButton>
  </div>
);

================  ================ 

 

 

================  ================  

================  ================  

================  ================  

 

'IT > Style(Library)' 카테고리의 다른 글

styled-components : styled.div` useState `  (0) 2021.11.10
문제 : [object Object] - styled-components  (0) 2021.11.10
Comments