공식문서 : https://styled-components.com/
vue styled-component: https://github.com/styled-components/vue-styled-components
1. 기본 사용법
- 컴포넌트를 생성하는 동시에 스타일을 정의할 수 있음
import styled from "styled-components"
const Father = styled.div`
display: flex;
color: royalblue;
`
function App() {
return(
<Father>
<div>1</div>
<div>2</div>
</Father>
)
}
2. prop
: styled-component 템플릿 리터럴의 함수에서 props를 받을 수 있다.
import styled from "styled-components"
const Father = styled.div`
display: flex;
`
const Box = styled.div`
width:100px;
height: 100px;
background-color: ${(prop)=>prop.bgColor};
`
function App() {
return(
<Father>
<Box bgColor='tomato' />
<Circle bgColor='teal' />
</Father>
)
}
3. Extending Styles
1) as : 태그만 바꾸기
const Btn = styled.button`
background-color: skyblue;
width: 100px;
height: 20px;
`
function App() {
return(
<Father>
<Btn/>
<Btn as="a" />
</Father>
)
}
2) Attrs : 속성을 갖는 스타일 컴포넌트 생성 가능
const InputEl = styled.input.attrs({required:true, maxLength:10})`
background-color: skyblue;
`
function App() {
return(
<>
<InputEl/>
</>
)
}
4. animations
- keyframes를 이용.
- css의 @keyframes를 사용하지 않는이유
: 컴포넌트에 스코핑 되지 않아, 글로벌로 선언되어 이름 충돌이 발생할 수 있기 때문이다.
: 스타일드 컴포넌트로 만들면 랜덤한 class명을 생성해주기 때문에 클래스명이 중복되지 않게됨.
import styled,{keyframes} from "styled-components"
const rotateAni = keyframes`
from{
transform: rotate(0deg);
}to{
transform: rotate(360deg);
background-color: teal;
}
`
const RotateBox = styled.div`
width: 100px;
height:100px;
background-color: tomato;
display: flex;
justify-content: center;
align-items: center;
animation: ${rotateAni} 2s infinite ;
`
function App() {
return(
<RotateBox>
<span>🥰</span>
</RotateBox>
)
}
5.가상선택자(pseudo selectors)
1) 태그명을 selector로 사용하기
2) styled-component자체를 selector로 사용하기
const ContentBox = styled.p`
font-size:20px;
`
const Wrapper = styled.div`
width: 100px;
height: 100px;
background-color: beige;
display: flex;
justify-content: center;
align-items: center;
/* 1) 태그명을 selector로 사용하기 */
p{
&:hover{
font-size:30px;
}
}
/* 2) styled-component자체를 selector로 사용하기 */
${ContentBox}{
&:active{
color: red;
}
}
`
function App() {
return(
<Wrapper>
<ContentBox>내용</ContentBox>
</Wrapper>
)
}
6. ThemeProvider
- 컨텍스트 API를 통해 ThemeProvider하위의 모든 컴포넌트에 테마를 제공함
- 하위 모든 컴포넌트에서 이 theme prop에 접근가능함
'프론트엔드 > React' 카테고리의 다른 글
Custom React 구현하기 (2) | 2024.12.22 |
---|---|
useState 의 setState는 비동적으로 동작 (0) | 2024.05.06 |
useMemo, useCallback에 대해 (0) | 2023.12.10 |
[TIL] React router6 (0) | 2023.09.17 |
a태그와 router-link 차이(spa) (0) | 2023.06.30 |