티스토리 뷰

📌개요
최근 회사에서 신규 프로젝트를 진행하는 과정에서 자식 컴포넌트에 있는 데이터를 부모 컴포넌트에 전달해야하는 작업이 필요했다. 예를들어 자식 컴포넌트에서 데이터 입력을 하면 그것을 부모 컴포넌트에서 데이터를 받아와서 다른 자식에게 전달해주는 작업이 필요했던 것이다. 이번 기회를 통해 리액트에서는 부모 자식간의 데이터 전달을 어떤식으로 통신하는지에 대해 알아보도록 하자!!
📌부모에서 자식으로 데이터 보내기
👉 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를 통해서 자식 컴포넌트에 해당 데이터를 전달해준다. 그 후 자식컴포넌트에서 데이터 변경이 감지되면 콜백함수를 이용해 다시 부모데이터가 변경되는 형식임!!
'WEB > React.js' 카테고리의 다른 글
[React] - 카카오 api를 활용하여 주소검색 기능 구현 (0) | 2023.03.13 |
---|---|
React 18 주요 변경점 (2) | 2023.01.17 |
React.js 3 - Fragments (0) | 2022.10.26 |
React.js 2 - Props & State 정리(2) (0) | 2022.10.26 |
React.js 2 - Props & State 정리(1) (0) | 2022.10.26 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
TAG
- 그림으로 이해하는 시스템 설계
- 알고리즘
- vue.js3
- store.js
- 구름톤
- 항해솔직후기
- 디자인시스템
- focus와blur
- event종류
- http
- 개발자
- eventListner
- 항해플러스프론트엔드
- 시스템설계
- react
- props
- Repository pattern
- 프로덕트설계
- 결제기능
- 더미데이터
- 로그인 인증
- 레포지토리패턴
- vue3
- 회고
- 이벤트리스너
- React18v
- Vue.js
- JWT토큰
- 항해플러스후기
- vite
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
글 보관함