본문 바로가기

Frontend/React

이미지를 출력하는 두 가지 방법

방법1 : import 하는 법

  • src 안에 images 폴더 생성 / 이미지 저장
  • 이미지를 사용하는 컴포넌트에서 이미지 import 하여 사용
import imgApple  from '../images/apple.png';
<img src={imgAppl} … />
// 이미지 출력

방법2 : public 내에 assets 폴더 만들고 그 안에 이미지 파일 저장

<img src='/assets/apple.png' ... >
// import 필요 없이 바로 이미지 출력 가능
import React, { Component } from 'react';
import imgApple from '../images/apple.png';
import imgBanana from '../images/banana.png';
import imgLizard from '../images/lizard.png';
import imgLizardon from '../images/lizardon.png';

class Image extends Component {
    state = {
        imgA:imgLizard,
        imgB:imgLizardon
    }

    render() {
        return (
            <div>
                {/* (1-1) : 이미지 import하여 사용 */}
                <img src={imgApple} alt='apple'/><img src={imgBanana} alt='banana'/><br/>
                
                {/* (1-2) : 이미지 import + state 활용 : 후에 다른 이미지로 변경 가능 */}
                <img src={this.state.imgA} alt='lizard'/>
                <img src={this.state.imgB} alt='lizardon'/>
                
                {/* (2) : public 접근하여 이미지 출력 */}
                <img src='/assets/black.png'/>
                <img src='/assets/pink.png'/><br/>
            </div>
        );
    }
}

export default Image;

'Frontend > React' 카테고리의 다른 글

MPA(Multiple Page Application) & SPA (Single Page Application)  (0) 2021.12.20
이벤트 처리 시 주의점  (0) 2021.12.20
state  (0) 2021.12.20
배열 비구조화 할당  (0) 2021.12.20
my-app 프로젝트  (0) 2021.12.17