티스토리 뷰

반응형

📌개요

최근 회사에서 신규 프로젝트를 진행하는 과정에서 자식 컴포넌트에 있는 데이터를 부모 컴포넌트에 전달해야하는 작업이 필요했다. 예를들어 자식 컴포넌트에서 데이터 입력을 하면 그것을 부모 컴포넌트에서 데이터를 받아와서 다른 자식에게 전달해주는 작업이 필요했던 것이다. 이번 기회를 통해 리액트에서는 부모 자식간의 데이터 전달을 어떤식으로 통신하는지에 대해 알아보도록 하자!!


📌부모에서 자식으로 데이터 보내기

👉 props를 이용한다.

props란 데이터를 전달하는 속성으로 부모 컴포넌트에서 설정할 수 있으며, 부모에서 자식으로만 데이터를 줄 수 있다.

Parent.js

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

const Parent = () => {
  const [number, setNumber] = useState(0);

  const onClick = () => {
    setNumber(number + 1);
  }

/*number가 props다.*/
  return (
    <div>
      <Child number={number}></Child>
      <button onClick={onClick}>+</button>
    </div>
  )
}

export default Parent;

Child.js

import React from 'react'

/*number는 props다.*/
const Child = ({ number }) => {
  return (
    <div>
      <p>여기는 child입니다 : {number}</p>
    </div>
  )
}

export default Child;

📌자식에서 부모로 데이터 보내기

👉콜백함수를 이용한다.

부모 컴포넌트에서 자식 컴포넌트로 콜백함수를 props로 전달하여, 자식 컴포넌트에서 이벤트가 발생했을 때 해당 콜백함수를 호출하도록 할 수 있다. 

Parent.js

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

function ParentComponent() {
  const [message, setMessage] = useState('');

  function handleMessage(message) {
    setMessage(message);
  }

  return (
    <div>
      <h2>Parent Component</h2>
      <p>Message from Child Component: {message}</p>
      <ChildComponent onMessage={handleMessage} />
    </div>
  );
}
export default ParentComponent;

Child.js

import React from 'react';

function ChildComponent({ onMessage }) {
  function handleClick() {
    onMessage('Hello from Child Component!');
  }

  return (
    <div>
      <h2>Child Component</h2>
      <button onClick={handleClick}>Send Message to Parent</button>
    </div>
  );
}

export default ChildComponent;

📌정리

정리하자면 부모컴포넌트에서 데이터를 정의한 후 props를 통해서 자식 컴포넌트에 해당 데이터를 전달해준다. 그 후 자식컴포넌트에서 데이터 변경이 감지되면 콜백함수를 이용해 다시 부모데이터가 변경되는 형식임!! 

반응형
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
글 보관함