지금까지 css작업은 SSAS로 진행했었다. css에서 SASS로 넘어가면서 편리함을 느꼈었는데 SSAS에서 styeld component로 작업 방식을 바꾸면서는 의문점이 많았다. 오히려 처음에는 더 불편함을 느꼈었던 것 같다. 그렇지만 좀 더 깊이 있게 사용해보면 분명 더 나은 기술임이 느껴진다.
// styled-components 라이브러리에서 import 해온 styled라는 객체를 이용한다
// 아래와 같이 h1 태그를 만들어 Title이라는 스타일드 컴포넌트를 만들 수 있습니다
import styled from 'styled-components'
render(
<Wrapper>
<Title>
Hello World!
</Title>
</Wrapper>
);
// html 태그 이름 뒤 Tagged Templete 문법을 활용해 CSS 속성을 정의하고 있다
//Templete Literals 문법(``)의 확장이라고 생각해도 좋다
const Wrapper = styled.section`
padding: 4em;
background: papayawhip;
`;
const Title = styled.h1`
font-size: 1.5em;
text-align: center;
color: palevioletred;
`;
가장 기본적이고 많이 쓰이는 항목이다.
아래에 코드에서 primary와 width부분을 props라 한다.
render(
<div>
<Button>Normal</Button>
<Button primary width="100">Primary</Button>
</div>
);
// 만약 Button 컴포넌트에 전달된 props(width)가 200 미만(조건)이면
// 삼항연산자 true : "palevioletred"
// 삼항연산자 false : "white"
const Button = styled.button`
background: ${props => props.width < 200 ? "palevioletred" : "white"};
color: ${props => props.primary ? "white" : "palevioletred"};
font-size: 1em;
margin: 1em;
padding: 0.25em 1em;
border: 2px solid palevioletred;
border-radius: 3px;
`;
기존에 만들어놓은 속성을 상속해주는 개념이다.
자주 사용하는 속성을 쓸때 사용해주면 좋을것 같다.
render(
<div>
<Button>Normal Button</Button>
<TomatoAnchorButton>Tomato Button</TomatoAnchorButton>
</div>
);
// The Button from the last section without the interpolations
const Button = styled.div`
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
// Button의 속성을 상속 받아 새로운 anchor 태그를 생성
const TomatoAnchorButton = styled(Button.withComponent("a"))`
color: tomato;
border-color: tomato;
`;