[React.js] Props로 데이터 전달하기

2024. 3. 10. 22:46Web/React.js

Props란?

부모 컴포넌트가 자식 컴포넌트에 값을 전달해준는것을 말한다.

 

App.js

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

Button.js

const Button = (props) => {
    return (
        <button>{props.text}</button>
    )
}

export default Button;

결과

이렇게 자식컴포넌트에게 props로 전달해서

전달한 props의 값을 자식컴포넌트가 사용할수 있다.

styil props 전달

 

App.jsx

<Button text={"메일"} color={"red"}/>

 

Button.jsx

<button style={{color: props.color}}>{props.text}</button>
    )

 

결과

styil도 자식컴포넌트에게 전달하여 사용할 수 있다.

 

부모컴포넌트에서 props에 아무것도 전달하지 않았을때

defaultProps 설정하는 방법

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

Button.defaultProps = {
    color: "black"
}

이렇게 설정하면

이런식으로 렌더링 하게 된다.

 

props를 안거치고 바로 객체를 꺼내어 사용하는 방법

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

Button.defaultProps = {
    color: "black"
}

export default Button;

props가 들어간 괄호() 안에 중괄호{}

를 넣고 꺼내오고자 하는 객체의 키값을 넣게된면 바로 사용할 수 있다.

const 변수안에 객체를 담아 스프레드연산자를 사용하여 props를 전달할 수동 있다.

 

App.jsx

function App() {

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

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

 

Button.jsx

const Button = ({text, color, a, b, c}) => {
    return (
        <button style={{color: color}}>
            {text} - {color} - {a} - {b} - {c}
        </button>
    )
}

 

결과

 

props는 HTML요소나 리액트 컴포넌트도 전달 할 수 있다.

 

App.jsx

<Button text={"블로그"}>
        <div>자식요소</div>
      </Button>

 

Button.jsx

<button style={{color: color}}>
            {text} - {color}
            {children}
        </button>

 

결과

 

이런식으로 HTML요소를 전달 할 수 있다.

 

App.jsx

import './App.css'
import Header from './components/Header.jsx'
import Main from './components/Main.jsx'
import Footer from './components/Footer.jsx'
import Button from './components/Button.jsx'

function App() {

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

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

export default App

Button.jsx

<button style={{color: color}}>
            {text} - {color}
            {children}
        </button>

결과

 

이렇게 리액트 컴포너트도

props 로 전달이 가능하다.

 

props는 부모 컴포넌트에서 자식컴포넌트로만 전달이 가능하다.

반대로 자식컴포넌트에서 부모컴포넌트로 props는 전달을 할 수가 없다.

반응형

'Web > React.js' 카테고리의 다른 글

[React.js] State - 상태 관리  (0) 2024.03.11
[React.js] 이벤트 핸들링  (0) 2024.03.11
[React.js] JSX로 UI 표현하기  (0) 2024.03.09
[React.js] 컴포넌트 개념  (0) 2024.03.09
[React.js] React 이론 및 App 생성 방법  (0) 2024.03.07