📑 개요
부모에서 자식으로 데이터를 전달하는 방법
- 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>;
</>
);
}
✨ 마무리
- 요약
'개발 > Front' 카테고리의 다른 글
[React] HTML과 React의 이벤트 처리 차이점 (0) | 2024.04.17 |
---|---|
[React] State를 쓰는 이유와 비동기 (0) | 2024.04.17 |
[React] Props란? Props Drilling과 해결 방법 (0) | 2024.03.21 |
[React] React의 불변성을 지키는 방법과 이유 (0) | 2024.03.21 |
[React] Pure Component와 렌더링 (0) | 2024.03.21 |