ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • TIL-2024.04.26 - React - 002-1. 단방향 통신 (Props & Callback)
    > Frontend/React 2024. 4. 27. 19:33

     

     

     

    질문:

    1. (내가 사용하던 Vue와 달리) React는 단방향 통신이라는데, 부모 <-> 자식간 데이터 통신을 어떻게 해? 

     

     

     

    CallBack 함수 

    - 콜백 함수(callback function)는 다른 함수에 인수로 전달되는 함수 (다른 코드의 인수로 넘겨주는 실행 가능한 코드)

    - 이러한 함수는 일반적으로 비동기적인 작업이 완료되었을 때 호출 | 다른 함수의 작업이 완료되었을 때 특정한 동작을 수행하기 위해 사용

    - 예를 들어, 파일을 읽거나 데이터베이스에서 데이터를 가져오는 등의 비동기적인 작업이 완료되었을 때 호출되는 함수를 지정 가능 &&
    이벤트 핸들러에서도 콜백 함수를 사용하여 특정 이벤트가 발생했을 때 실행될 코드를 정의 가능.

     

     

     

    Callback 함수 예제 

    function greet(name, callback) {
      console.log('Hello, ' + name + '!');
      callback(); // 콜백 함수 호출
    }
    
    function sayGoodbye() {
      console.log('Goodbye!');
    }
    
    greet('Alice', sayGoodbye); // sayGoodbye 함수가 콜백으로 전달됨

     

     

     

    React에서의 Data Flow

     

     

     

     

    - props로 Parent에서 Child로  데이터를 전달, 콜백 함수를 통해 Child에서 Parent로 이벤트를 전달.

    - Parent에서 Child로 데이터를 전달하기 위해서는 props를 사용. 이 데이터는 Parent에서 변경 가능.

    - Child에서 Parent로 이벤트를 전달하기 위해 콜백 함수를 props로 전달하고, Child 내에서 콜백 함수를 호출하여 이벤트를 트리거.

     

     

     

     

    // ParentComponent.js
    import React, { useState } from 'react';
    import ChildComponent from './ChildComponent';
    
    const ParentComponent = () => {
      const [data, setData] = useState('');
    
      const handleEventFromChild = (dataFromChild) => {
        // 부모 컴포넌트에서 이벤트를 처리하는 로직
        console.log('Received data from child:', dataFromChild);
        setData(dataFromChild);
      };
    
      return (
        <div>
          <ChildComponent onDataReceived={handleEventFromChild} />
          <p>Data from child: {data}</p>
        </div>
      );
    };
    
    export default ParentComponent;

     

     

     

    // ChildComponent.js
    import React, { useState } from 'react';
    
    const ChildComponent = ({ onDataReceived }) => {
      const [inputValue, setInputValue] = useState('');
    
      const handleChange = (e) => {
        setInputValue(e.target.value);
      };
    
      const sendDataToParent = () => {
        // 자식 컴포넌트에서 부모 컴포넌트로 데이터 전달
        onDataReceived(inputValue);
      };
    
      return (
        <div>
          <input type="text" value={inputValue} onChange={handleChange} />
          <button onClick={sendDataToParent}>Send Data</button>
        </div>
      );
    };
    
    export default ChildComponent;

     

     

     

    - 위 예제에서 ParentChildonDataReceived라는 이름의 콜백 함수를 props로 전달하고, Child는 이 콜백 함수를 호출하여 데이터를 Parent로 전달

     

     

    답변:

    1. React는 단방향 통신이라는데, 부모 <-> 자식간 데이터 통신을 어떻게 해? 

    - Props를 통해서 부모에서 자식으로, 콜백 함수를 호출하여 Child 에서 부모로 데이터 통신. 

     

     

     

    댓글

Designed by Tistory.