개발/Front

[React] '부모 -> 자식' or '자식 -> 부모' 의 데이터 전달 방법

차뀨뀨 2024. 3. 21. 12:55

 

 

📑 개요

 

 

 

 

 


 

 

 

 

부모에서 자식으로 데이터를 전달하는 방법

 

- props 사용

 

부모 컴포넌트에서 데이터를 변경하는 함수를 props로 전달하고

자식 컴포넌트에서 전달받은 함수를 호출하여 데이터를 변경한다.

 

자식은 props를 통해 부모에게 데이터를 줄 수 없다.

 

 

Parent.js

import { useState } from "react";
import Child from "../../components/Child";

export default function Dev() {
	const [name, setName] = useState("ChaCha");
    
	return <Child name={name}></Child>;
}

 

Child.js

export default function Child(props) {
  return <p>{props.name}</p>;
}

 

 

 

 


 

 

 

자식에서 부모로 데이터를 전달하는 방법

 

- 함수 사용

자식은 props를 통해 부모에게 데이터를 줄 수 없기 때문에,

부모 컴포넌트 state를 변경하는 함수를 Props를 통해 전달하고

자식 컴포넌트는 부모에서 받은 함수를 호출하여 데이터를 변경한다.

 

 

Parent.js

import { useState } from "react";
import Child from "../../components/Child";
 
export default function Dev() {
  const [name, setName] = useState("ChaCha");
  function onSetName(name: string) {
    setName(name);
  }
 
  return (
    <>
      <Child updateName={onSetName}></Child>
      <p>{name}</p>
    </>
  );
}

 

Child.js

export default function Child(props) {
  function updateName() {
    props.updateName("ggyu");
  }
 
  return (
    <>
      <p>{props.name}</p>
      <button onClick={updateName}>ChangeName</button>;
    </>
  );
}

 

 

 

 


 

 

 

✨ 마무리

 

 

 

- 요약