본문 바로가기
css

스타일링된 구성요소의 사용자 지정 구성요소에 오신 것을 환영합니다!

by code-box 2022. 3. 9.
반응형

리액트 또는 유사한 JS 라이브러리를 연습하는 경우 여러 개의 div 또는 HTML 태그를 만드는 작업이 종종 복잡합니다. 그리고 HTML 태그로 스타일링하고 관리하는 것도 힘든 일입니다.

자신만의 맞춤식 Stlyed 구성 요소를 만들기 위해 "Styled-Components"는 이러한 유형의 작업에 널리 사용되는 솔루션입니다.

*스타일 구성 요소란? *

스타일 구성 요소의 몇 가지 이점:

  • 개인 설정된 구성 요소 이름
  • 클래스 이름 충돌 없음
  • CSS의 손쉬운 삭제 및 문제 해결
  • 소품 값을 사용한 동적 스타일링
  • 기본 CSS, Easy Maintanece 등.
 

이게 뭔지 기본적인 생각을 했으니까.

기본 사항에 대해 살펴보기 전에 설치 방법에 대해 알아보겠습니다.


# with npm
npm install --save styled-components

# with yarn
yarn add styled-components

기본 사항
그것을 파헤쳐 보자.
Style-components 포맷의 기본은 다음과 같다.


const ComponentName = styled.h1`
    font-size: 1em; 
        color: red; 

 

이러한 유형의 구성요소 작성은 동일한 파일에서 수행하거나 별도의 파일에도 작성할 수 있습니다.

실제 스타일링을 살펴볼 경우 전체 뷰는 다음과 같습니다.


// 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;
    `;

// Use Title and Wrapper like any other React component – except they're styled!
render(
    <Wrapper>
      <Title>
        Hello World!
      </Title>
    </Wrapper>

  //source: styled-components documentation

기존 태그 재사용

또한 우리는 다음과 같은 기존 스타일 구성 요소를 재사용할 수 있습니다.

 

const Button = styled.button`
     color: red;
          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(Button)`
  color: tomato;
    border-color: tomato;

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

특성 사용 위치
스타일링된 컴포넌트는 유사한 컴포넌트를 재사용할 수 있는 소품을 가질 수 있습니다. 예를들면


const Headline = styled.h1`
  color: ${props => props.color};
  `

function App() {
    return (
          <>
          <Headline color="red">
            Text 
          </Headline>
          <Headline color="blue">
            Text 
          </Headline>
          </>
        )
}

조건 특성
이러한 소품은 동적 입력이므로 조건부 경우에 사용할 수 있습니다.


const Headline = styled.h1`
  visibility: ${props => (
        props.show ? "visible" : "hidden")
};`

function App() {
    return (
          <Headline show={false}>
            Text 
    </Headline>
  )
}
 

이것들은 스타일링된 구성 요소의 기본 사항입니다.
또한 스타일링된 컴포넌트는 고급 용도가 있습니다.
자세한 내용은 구성 요소 유형 설명서를 참조하십시오. https://styled-components.com/docs/basics#motivation

댓글