Web/React

[React] 컴포넌트간 데이터 이동 Props

usingsystem 2023. 4. 20. 15:23
728x90

React 컴포넌트는 부모의 값이 변경되면 하위 컴포넌트도 다시 랜더링 되며 자신의 값이 변경되어도 동일하게 다시 랜더링 된다.

부모에서 자식 간 Props 전달

App.js

import React from 'react';
import MyHeader from './MyHeader';
import Counter from './Count';


function App() {
const number = 5;

const counterProps ={
  a:1,
  b:2,
  c:3,
  d:4,
  e:5,
}

  return (
    <div>
     <MyHeader/>
     <Counter {...counterProps}/>
    </div>
  );
}

export default App;

자식 컨포넌트인 Counter에게 ...연산자를 사용하여 객체 자체를 넘겨줄 수 있다. 이를 props라고 한다.

 

Counter.js

import React,{useState} from 'react';
import OddEvenResult from './OddEvenResult';

const Counter = ({initialValue}) =>{

    console.log(initialValue);
    const [count, setCount, ads] = useState(initialValue);

    const onIcrease = ()=>{
        setCount(count + 1);
    }

    const onDecrease = () =>{
        setCount(count -1);
    }

    return (
        <div>
            <h2>{count}</h2>
            <button onClick={onIcrease}>+</button>
            <button onClick={onDecrease}>-</button>
            <OddEvenResult count ={count}/>
        </div>
        );
    }

Counter.defaultProps ={
    initialValue :0,
}

export default Counter;

App.js의 컨포넌트인 counter는 initialValue로 전달 받으며 부모에서 initialValue데이터를 전달 하지 않기 때문에 counter.defaultProps를 사용하여 초기값을 할당하면 undefined가 일어나지 않는다.

 

 

컨포넌트를 다른 컨포넌트에게 Props로 전달 하는 방법

 

App.js

import React from "react";
import MyHeader from "./MyHeader";
import Counter from "./Count";
import Container from "./Container";

function App() {
  const number = 5;

  const counterProps = {
    a: 1,
    b: 2,
    c: 3,
    d: 4,
    e: 5,
  };

  return (
    <Container>
      <div>
        <MyHeader />
        <Counter {...counterProps} />
      </div>
    </Container>
  );
}

export default App;

디자인을 담당하는 Container.js로 하위 컨포넌트를 감쌓면 Container.js에 하위 컨포넌트가 Props로 전달받게 된다.

 

Container.js

const Container = ({ children }) => {
  console.log(children);
  return (
    <div style={{ margin: 20, padding: 20, border: "1px solid gray" }}>
      {children}
    </div>
  );
};

export default Container;

children은 react.elemet를 전달 받게된다.

728x90