Styled-Components - ThemeProvider

최문길·2023년 11월 15일
2

ThemeProvider 안에 있는 styled-component들이라면 props 전달 안해줘도 쓸 수 있다.


 <ThemeProvider theme={{ color: red }> // theme은 객체 형태로 넣어줘야 함
   <Styled-Component> // 이렇게 해주고 styled
 </ThemeProvider>

 const Styled-Component = styled.div`
  padding: 0.5rem 1rem;
  height: 100%;
  img {
    width: 120px;
    height: 100%;
  }
background : ${props=> props.theme.color}
// 일반적으로 전달 하는거 안써줘두 댐 알아서 전역으로 뿌리고 있으니...!!
`;

ThemeProvider에는 속성 값에 theme이라는 것이 있고 그 theme 안에는 '객체' 형태로 넣어줘야 한다.

우리가 일반적으로 부모 요소에서 자식요소에게 props 전달 할 때

    <Parent>
    	<Child props={props} />
    </Parent>
    

를 써주는 것이 맞지만

ThemeProvider 하위에 있는 styled-component에는 props전달을 명시 하지 않아도 props를 사용 할 수 있다.

		<ThemeProvider theme={ { . . .} }>
           <StyledComponent> 
        </ThemeProvider>
        
     const StyledComponent =  styled.div`
     background : ${ props=> console.log( props ) } // {className: undefined, theme: {…}}
     `

위 코드에서 props를 명시 하지 않아줬지만,
ThemeProvider의 theme 값이 props로 콘솔 찍었는데 나오는 것을 볼 수 있다.

0개의 댓글