부모 자식간의 데이터 교환 (parent&child data passing)

ryuyh2000·2022년 2월 8일
0

#React

목록 보기
1/4

props를 통해 부모에서 자식으로 보내는 작업은 많이 해 보았다.
예를 들어

//parent.tsx
import React from "react";
import Child from "./child";



const parent=()=>{
	return(
    	<>
			<Child name={"김찬호"}/>
    	</>
	)
}

=====
//child.tsx
import React from "react;

interface childProps{
	name:string;
}

const Child:React.FC<childProps>=({name})=>{
	return(
    	<div>{name} 입니다.</div>
	)
}

위와 같이 parent 에서 name(김찬호)라는 데이터를 보내 child에서 props로 받아
return부분에 name 데이터를 받아 출력하는 코드이다. 즉 parent=>child 로 가는 방식인것이다. 이런 방식은 많이 짜 봤지만 정작 child=>parent은 시도해보지 않았다. 그래서 찾아보니 callback 함수를 사용하면 되는 것 이였다.

callback 함수는 이미 많은 사람이 설명을 해 놓았지만 내 특성상 다른사람이 정의를 설명해주는 것은 이해도 잘 못할 뿐더러 어렵게 느껴질때가 많았다. 그래서 항상 내 방식으로 이해를 많이 하는 편이다. 물론 다른 사람도 내 방식으로 해석할 수 있다. 아무튼 callback을 한글로 해석하면, '다시 불러오다' 라는 뜻으로 해석이 가능하다. 그렇다면 코딩에서 다시 불러오는 것은 보통은 '정보'일 것이다. 정보 반환이라고 해석하게된다. 내 멋대로 해석한것이기에 틀렸을 수도있다. 예를 또 들어보자

//parent.tsx
import React from "react";
import Child from "./child";



const Parent=()=>{

	const print=(text:string)=>{
    	console.log(text);
    }
	return(
    	<>
			<Child name={"김찬호"} parentCallback={print}/>
    	</>
	)
}

export default Parent;

=====
import React from "react";

interface childProps {
  name: string;
  parentCallback: (text: string) => void;
}

const Child: React.FC<childProps> = ({ name, parentCallback }) => {
  const [text, setText] = React.useState("");

  const typing = (event: React.ChangeEvent<HTMLInputElement>) => {
    const {
      target: { value },
    } = event;
    setText(value);
  };

  React.useEffect(() => {
    parentCallback(text);
  });

  return (
    <>
      <div>{name} 입니다.</div>
      <input onChange={typing} />
    </>
  );
};

export default Child;

위 코드와 같이 child 쪽에 callback 함수를 만들어 parent에서 함수를 넘겨 child에서 생성된 정보를 넣어 다시 반환하는 식인것이다. 위 코드의 결과는

이렇게 나오게 된다. callback 함수의 중요성을 다시 한번 느낄 수 있었다.

3줄요약)
callback에 대한 무지함에 폐해
부모(page) <=> 자식(component) 서로 데이터 교환 가능
지식이 또 늘었다.

profile
응애 프론트앤드 개발자

0개의 댓글

관련 채용 정보