styled-component_React

miin·2021년 10월 18일
0

React

목록 보기
19/52
post-thumbnail

정의

  • 변수처럼 사용할 수 있다
  • style이 적용된 component를 직접 생성하기 때문에 스타일링을 위한 코드 사용량이 줄어드는 장점이 있다
  • key value의 형태가 아닌 css의 문법을 그대로 사용하기에 기존 css의 사용법보다 가독성이 높다
  • npm install --save styled-components 설치
  • import styled from 'styled-components';
  • const Button = styled.button``;
    const 변수명(첫글자 대문자) = styled.요소`style`;

기존 css 스타일링 방식

const divStyle = {
    backgroundColor: "black",
    width: "100px",
    height: "100px",
  };

  return <div style={divStyle}></div>
 
styled-components를 사용한 방식

  const StyledDiv = styled.div`
    background-color: black;
    width: 100px;
    height: 100px;
  `;

  return <StyledDiv></StyledDiv>

조건부 스타일링

props를 전달받아 사용,
내부에서 선언된 함수는 props를 파라미터로 실행된다.

const StyledDiv = styled.div`
    background-color: black;
    width: 100px;
    height: 100px;
    ${({ login }) => {
      return login ? `display: none` : null;
    }}
  `;
  return <StyledDiv login={true}></StyledDiv>;
//or
const Button = styled.button` ... background-color:
${(props) => (props.danger ? '#e74c3c' : '2ecc71')}; } `;

출처: https://xtring-dev.tistory.com/entry/Styling-Styled-Components-이해하고-사용하기-💅 [xtring.dev]

확장 스타일링

중복된 코드양을 줄이고,
분산된 스타일을 일관적으로 관리 할 수 있다.

//부모 스타일링
const Container = styled.div`
    max-width: 600px;
    width: 100%;
    height: 100px;
  `;
//자식으로 활용
  const BlackContainer = styled(Container)`
    background-color: black;
  `;
  const RedContainer = styled(Container)`
    background-color: red;
  `;
  return (
    <>
      <BlackContainer />
      <RedContainer />
    </>
  );
const MyLink = styled(Link)`
    color: black;
    text-decoration: none;
  `;
  return (
    <Router>
      <MyLink to="/main"> 커스텀 링크 </MyLink>
    </Router>
  );

중첩 스코프

const StyledDiv = styled.div`
    background-color: black;
    width: 100px;
    height: 100px;
    p {
      color: white;
    }
  `;
  return (
    <>
      <StyledDiv>
        <p>Title</p>
      </StyledDiv>
      <p>content</p>
    </>
  );

theme 사용

const Button = styled.button`
  font-size: 1em;
  margin: 1em;
  padding: 0.25em 1em;
  border-radius: 3px;
  color: {({theme}) => theme.color};
  border: 2px solid {({theme}) => theme.color};
`;

attrs 속성

const TextInput = styled.input.attrs({
  type: "text",
  required: true,
  placeholder: "스타일 컴포넌트 꿀템!"
})`
  color: red;
`;

0개의 댓글