확장성 사용하기

yonghee·2022년 5월 23일
0

styled-components

목록 보기
3/6
import styled from 'styled-components';

const Father = styled.div`
  display: flex;
`;

const BoxOne = styled.div`
  background-color: teal;
  width: 100px;
  height: 100px;
`;
const BoxTwo = styled.div`
  background-color: tomato;
  width: 100px;
  height: 100px;
`;

function App() {
  
  return (       
  	<Father>
      <BoxOne />
      <BoxTwo />
    </Father>    
  )
}

앞서 기본적으로 적용한 BoxOne과 BoxTwo 코드를 보면 background-color 색을 제외하고는 같은 코드이다 여기서 드는 생각은 반복되는 코드를 사용하고 싶지 않을수 있다.

props 사용하기

const Father = styled.div`
  display: flex;
`;

const Box = styled.div<{ boxColor: string }>`
  background-color: ${(props) => props.boxColor};
  width: 100px;
  height: 100px;
`;

<Father>
  <Box boxColor="blue" />
  <Box boxColor="red"/>
</Father>

props를 사용하는 문법도 쉽게 적용이 가능합니다. boxColor라는 값을 임의로 지정하고 각각의 컴포넌트에 내려주기만 하면된다 typescript를 사용하는 경우에는 임의로 지정한 값에 대한 타입을 지정해 줘야 합니다 <{ boxColor: string }> css도 props 통해 작업이 가능한 것은 멋진 것 같습니다.🤩

profile
필요할 때 남기는 날것의 기록 공간

0개의 댓글