부모 컴포넌트에서 자식 컴포넌트로 데이터를 전달하는 방법과 자식 컴포넌트에서 부모 컴포넌트로 데이터를 전달하는 방법입니다.
ReactJS, NextJS에서 props를 사용하여 간단하게 데이터를 전달하는 방법입니다.
요즘 자꾸 깜빡깜빡해서 적어둔 내용입니다.
1. 부모 컴포넌트에서 자식 컴포넌트로 데이터 전달하기
Parent Component --> Child Component
Parent.tsx
import ...
const Parent = () => {
const [data, setData] = useState<string>("문자열");
return (
<>
<Child data={data}></Child>
</>
);
}
export default Parent;
Child.tsx
import ...
const Child = ({ data }: { data: string}) => {
console.log(data);
return (
<>
<div>
Child Page
</div>
</>
);
}
export default Child;
2. 자식 컴포넌트에서 부모 컴포넌트로 데이터 전달하기
Child Component --> Parent Component
Parent.tsx
const Parent = () => {
const parentFunc = (str: string) => console.log(str);
return (
<>
<Child parentFunc={parentFunc}></Child>
</>
);
}
export default Parent;
Child.tsx
const Child = ({ parentFunc }: { parentFunc: Function }) => {
const [data, setData] = useState("Hello World");
parentFunc(data);
return (
<>
<div>Child</div>
</>
);
}
export default Child;
'React > NextJS' 카테고리의 다른 글
| [ NextJS ] Uncaught DOMException: Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node. (0) | 2023.07.20 |
|---|---|
| [ NextJS ] router.push()를 통해 데이터 전달하기 (0) | 2023.07.13 |
| [ NextJS ] 뒤로가기 방지하기 (2) | 2023.05.16 |
| [ NextJS ] input type="file"에 같은 파일 연속으로 올리기 (0) | 2023.05.15 |
| [ NextJS ] input multiple image 추가하기 (0) | 2023.05.12 |
