수니아이티

[styled-component]img태그의 src 값 Props로 전달 본문

React

[styled-component]img태그의 src 값 Props로 전달

포도메론 2021. 7. 29. 15:26

Props를 통해서 스타일링 하는 방법

const Button = styled.button`
    /* 
    props로 넣어 준 값을 전달 받을 수 있다.
    Button 컴포넌트에서 color="yellow" 값을 props로 전달하였고, 
    전달된  props 값이 없으면 blue값을 사용 한다.
    */
    background-color: ${(props) => props.color || "blue"}; 
`;


const App = () => {
	return (
		<Container>
    		<Button color="yellow">버튼</Button>
    	</Container>
	)
}

export default App;

img태그의 src 속성을 Props 로 전달하는 방법

* props를 허용하는 올바른 attrs 형식은 props를 사용하고 객체를 반환하는 함수를 정의하는 것이다.

const Icon = styled.img.attrs((props) => ({
  src: props.imdbImage,
}))`
  width: 60px;
  height: 60px;
`;

/* props(imdbImage)로 이미지 경로 전달*/
<Icon imdbImage={require("../../assets/imdb.png").default}></Icon>

 

'React' 카테고리의 다른 글

[React]render 시 a태그의 값을 동적으로 변경하는 방법  (0) 2021.07.29
Comments