본문 바로가기
  • search_ _ _ _
  • search_ _ _ _
  • search_ _ _ _
React & JSX

리엑트 컨포넌트 이미지 및 스타일 넣기

by 오늘의갈비찜 2024. 12. 3.
728x90

1. 이미지 외부에서 호출하기

assets/images/이미지명

 

 

 

- 클래스 컨포넌트에서 작업

import React from "react";

class Hello extends React.Component{

    static defaultProps = {
        image : 'cute_puppy',
        label : '귀여운 강아지입니다.'
    }

     //사용자 정의 메소드
     getImageURL(){
        const image = this.props.image;
        const url = require(`../assets/images/${image}.png`);
        return url;
    }

    render(){
        //const image = this.props.image;  //this 필수
        const image = this.getImageURL();
        const label = this.props.label;


        //css
        const boxStyle = {
            border : "4px solid blue",
            margin : "8px",
            padding : "4px",
        }

        return (
            <div style={boxStyle}>
                <img src={image} width={128} alt={label} />   
                {/* width={128} , width="128" 둘 다 가능 */}
                <span>{label}</span>  
            </div>
        )
    }
}

export default Hello;

 

 

 

 

 

- 화살표 함수에서 작업

const Hello2 = (props) => {

    //화살표는 함수이므로 this를 사용할 경우 앱을 가르키게됨

    //const image = props.image;  
    const getImageURL = () => {
        const image = props.image;
        const url = require(`../assets/images/${image}.png`);
        return url;
    }

    const image = getImageURL();

    const label = props.label;

    //css
    const boxStyle = {
        border : "4px solid green",
        margin : "8px",
        padding : "4px",
    }


    return (
        <div style={boxStyle}>
            <img src={image} width={128} alt={label} />   
            <span>{label}</span>  
        </div>
    )
   }
   
   export default Hello2;

 

 

 

- function함수에서 작업

function Hello3({image='cute_puppy', label='귀여운 강아지입니다.'}) {
    //props 감춰져 있음 = 매개변수와 같다고 생각해보면 무난
    //데이터가 없을시 노출되는 값
    // 단점은 전부 채워야함.. 아니면 뒤 부터 채워야함..
    
   //css
   const boxStyle = {
    border : "4px solid pink",
    margin : "8px",
    padding : "4px",
    }


    const getImageURL = () => {
        const url = require(`../assets/images/${image}.png`);
        return url;
    }

    //const image2 = getImageURL();


    return (
        <div style={boxStyle}>
            {/* <img src={image2} width={128} alt={label} />   */}
            <img src={getImageURL()} width={128} alt={label} />   
            <span>{label}</span>  
        </div>
    )
}

export default Hello3;

 

728x90