[React]styled-components

LateMarch·2023년 2월 18일
0

기본 사용법

// 기본 사용법
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*/
  }
`

Themes and styled-components

Props 전달해주기

하위 컴포넌트가 상위 컴포넌트로부터 props를 받을 수 있는것 처럼 styled-componentsprops를 받아 활용 할 수 있다.

const Div = styled.div`
  color: ${(props) => props.textColor};
`
...

<Div textColor="black" />

테마 적용하기

props를 전달할 수 있다는 말은 스타일 요소가 동적으로 변할 수 있다는 말이다. 이를 이용하면 페이지의 테마 또한 동적으로 설정 할 수 있다. 먼저 styled-componentsThemeProvider를 import해준 뒤, 사용 될 테마 설정을 해준다. 그리고 설정한 테마로 적용 될 컴포넌트 들을 감싸준다.

import {ThemeProvider} from "styled-components";
	...
  const darkTheme = {
    textColor: "white";,
    backgroundColor: "black";
    ...
  }

	...
	<ThemeProvider theme={darkTheme}>
  	  <App />
  	<ThemeProvider />
	...

그럼 이제 App 컴포넌트와 그 하위 컴포넌트들의 styled-componentsThemeProvider가 제공해 주는 darkThemeprop으로 받을 수 있게된다. 따라서 App 컴포넌트 안에서 styled-components를 이용하여 다음과 같이 사용 될 수 있다.

// App.jsx 의 styled-components
const Text = styled.span`
  color: ${(props) => props.theme.textColor};
`

이를 이용하여 lightTheme등, 같은 속성명을 가지는 여러 테마들을 만들어 놓고 ThemeProvidertheme으로 전달해주는 객체를 바꿔주면 쉽게 테마를 변경할 수 있다.

profile
latemarch

0개의 댓글