셋째주 #12 react js - styled-components

김선은·2023년 5월 29일

styled-components

Pseudo selectors와 스타일 컴포넌트를 셀렉터로 사용

const Box = styled.div`
  height: 100px;
  width: 100px;
  background-color: ${(props) => props.bgColor}
  span {  // 1. 스타일 컴포넌트 내부 tag를 target해서 css 입히기. (Pseudo selectors)
    font-size: 36px
    &:hover {font-size: 50px}
  }
  ${emoji} {font-size: 90px} // const emoji = styeld.div``
  // 2. 또는 span 이라는 html tag 대신 만든 스타일 컴포넌트 타켓팅이 가능하다.
`
const Circle = styled(Box)`
  border-radius: 50px;
`

style 작성 부분과 구현 부분이 구분되어 있는 장점

한두가지 스타일만 다른 컴포넌트, 코드 중복 피하는 방법
1. 구현 부분에 props 설정
- 컴포넌트에 데이터를 보내는 방식
2. 컴포넌트 확장(extends)
- 스타일 컴포넌트 생성시 html el 대신 상속 받고싶은 컴포넌트 이름 입력.
ex) const Circle = styled(Box)``

as 와 Attrs

  • as : 명시적으로 html 태그를 변경시킴
    - Btn의 as와 href는 styled-components의 속성
const Btn = styled.button``
<Btn as="a" href="/" />
  • attrs : 컴포넌트에서 디폴트로 쓰고싶은 속성을 가진 오브젝트를 담는 방법
    html attribute(속성)을 개별마다 적용시킬 필요가 없어짐.
    const Input = styled.input.attrs({ required: true})

스타일 컴포넌트 애니메이션

  • keyframes을 import

keyframes helper를 사용하면 앱 전체에서 사용할 수 있는 고유한 인스턴스를 생성!
animation 이름도 class처럼 무작위로 생성되기에 다른 파일에서 같은 이름의 keyframes가
존재하더라도 이름 충돌이 나지 않는다.

  • 애니메이션 만들기
const rotationAnimation = keyframes`
    from {
      transform: rotate(0deg);
    }
    to {
      transform: rotate(360deg);
    }
    // from과 to 대신 0%, 50%, 100% 로 줄 수 있다.
`
  • 애니메이션 사용하기
    적용을 원하는 스타일 컴포넌트 작성부분에 animation 속성에 입력
const Btn = styled.button`
  animation: ${rotationAnimation} 1s linear infinite
  // 길이는 1초, 일정하게(정비례), 무한하게
`

스타일 컴포넌트 테마(Themes)

theme : 색상을 가지고 있는 object. 컴포넌트의 색을 일일이 바꾸지 않고 특정 object만 바꿔주면 됨

  1. ThemeProvider를 styled-components로 부터 import 한다
  2. index파일에서 App 컴포넌트를 ThemeProvider로 감싼다
  3. const darkTheme = {} 만들고 ThemeProvider 컴포넌트에 속성으로 theme={darkTheme} 넣기
const darkTheme = {
	textColor: "whitesomke"
    backgroundColor: "black"
} // 구체적인 색상 지정
// 타 컴포넌트가 Theme object에 접근해서 textColor를 얻을 수 있다.

<ThemeProvider theme={darkTheme}>
// 사용 준비작업(theme로 접근 가능하게)
// App을 감싸고 있으니 App 하위에서 전부 darkTheme 속성에 접근 가능.
  
const Title = styled.h1`
	color: ${(props) => props.theme.textColor};
`
profile
기록은 기억이 된다

0개의 댓글