본문으로 바로가기

[REACT] Props 사용법

category 나의 주니어 개발 일기/REACT 2025. 4. 25. 14:05
728x90
반응형
SMALL

컴포넌트에 값 전달하기 Props

const Button = (props) => {
    console.log(props);
    return <button style={{color: props.color}}>
        {props.text}
        </button>
};

export default Button;


function App() {
  return (
    <>
      <Button text={"메일"} color={"red"}/>
      <Button text={"카페"}/>
      <Button text={"블로그"}/>
    </>
  );
}

export default App;

 

 

만약에 color가 없을때 디폴트 값을 설정하고 싶다면? 구조분해할당 방법 적용

const Button = ({text, color = "black"}) => {
    return (
        <button style={{color: color}}>
            {text} - {color}
        </button>
    );
};


export default Button;

 

Spread 연산자를 이용해서 Props 일괄적으로 전달하기

function App() {
  const buttonProps = {
      text : "메일",
      color : "red",
      a : 1,
      b : 1,
      c : 1,
  };

  return (
    <>
      <Button {...buttonProps}/>
      <Button text={"카페"}/>
      <Button text={"블로그"}/>
    </>
  );
}

export default App;

//=============================================
const Button = ({text, color = "black"}) => {
    return (
        <button style={{color: color}}>
            {text} - {color}
        </button>
    );
};

export default Button;

 

Html 요소도 전달가능, 자식요소는 children 이라는 구조분해할당 기법으로 전달받을 수 있다.

function App() {

  const buttonProps = {
      text : "메일",
      color : "red",
      a : 1,
      b : 1,
      c : 1,
  };

  return (
    <>
      <Button {...buttonProps}/>
      <Button text={"카페"}/>
      <Button text={"블로그"}>
        <div>자식 요소</div>
        <HeaderV1/>
      </Button>
    </>
  );
}

export default App;

//=============================================
function HeaderV1(){
    return (
      <header>
        <h1>header</h1>
      </header>
  
    );
  }
  
  const HeaderV2 = () => {
    return (
      <header>
        <h1>header</h1>
      </header>
  
    );
  }

  export default HeaderV1;


//=============================================
const Button = ({children, text, color = "black"}) => {
    return (
        <button style={{color: color}}>
            {text} - {color}
            {children}
        </button>
    );
};



export default Button;

728x90
반응형
LIST

'나의 주니어 개발 일기 > REACT' 카테고리의 다른 글

[REACT] CSS 적용법  (1) 2025.04.25
[REACT] Main 사용법  (0) 2025.04.25
[REACT] JSX 사용법  (0) 2025.04.25
REACT는 왜 사용할까?  (0) 2022.10.26