// 기본 사용법
const Div = styled.div`
/*style*/
`
// 상속하기
const Div2= styled(Div)`
/*style*/
`
// Attributions 넣기
const InputWithAttrs = styled.div.attrs({required : true})`
/*style*/
`
// Animation 넣기
const rotation = keyframes`
from {
transform:rotate(0deg);
}
to {
transform:rotate(180deg);
}
`
const Div = styled.div`
/*style*/
animation: ${rotation} 1s linear;
`
//컴포넌트 안의 테그에 스타일 넣기
const Box = styled.div`
/*style*/
span {
/*style*/
&:hover{
/*style*/
}
}
${Component} {
/*컴포넌트를 직접 넣을 수도 있음*/
/*style*/
}
`
Props
전달해주기하위 컴포넌트가 상위 컴포넌트로부터 props
를 받을 수 있는것 처럼 styled-components
도 props
를 받아 활용 할 수 있다.
const Div = styled.div`
color: ${(props) => props.textColor};
`
...
<Div textColor="black" />
props
를 전달할 수 있다는 말은 스타일 요소가 동적으로 변할 수 있다는 말이다. 이를 이용하면 페이지의 테마 또한 동적으로 설정 할 수 있다. 먼저 styled-components
의 ThemeProvider
를 import해준 뒤, 사용 될 테마 설정을 해준다. 그리고 설정한 테마로 적용 될 컴포넌트 들을 감싸준다.
import {ThemeProvider} from "styled-components";
...
const darkTheme = {
textColor: "white";,
backgroundColor: "black";
...
}
...
<ThemeProvider theme={darkTheme}>
<App />
<ThemeProvider />
...
그럼 이제 App
컴포넌트와 그 하위 컴포넌트들의 styled-components
는 ThemeProvider
가 제공해 주는 darkTheme
을 prop
으로 받을 수 있게된다. 따라서 App
컴포넌트 안에서 styled-components
를 이용하여 다음과 같이 사용 될 수 있다.
// App.jsx 의 styled-components
const Text = styled.span`
color: ${(props) => props.theme.textColor};
`
이를 이용하여 lightTheme
등, 같은 속성명을 가지는 여러 테마들을 만들어 놓고 ThemeProvider
에 theme
으로 전달해주는 객체를 바꿔주면 쉽게 테마를 변경할 수 있다.