Web/React
React 자식 컴포넌트에서 부모 컴포넌트 데이터 변경하기
__bo0o_
2021. 5. 31. 01:07
보기 쉽게 정리하려 포스팅합니다.
1. 부모 컴포넌트
import React from "react";
import ChildComponent from "../ChildComponent/ChildComponent";
export default class ParentsComponent extends React.Component {
parentsFunction = (idx) => {
console.log(idx);
}
render() {
const exData = "data";
return (
<ChildComponent
exData={exData} // 변수 전달
exData2="hi" // 문자 전달
parentsFunc={this.parentsFunction} /> // 함수 전달
)
}
}
먼저 자식 컴포넌트로 함수를 전달하고
2. 자식 컴포넌트
import React from "react";
export default class ChildComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
exData: this.props.exData,
exData2: this.props.exData2
}
}
childFunction = (idx) => {
this.props.parentsFunc(idx);
}
render() {
const { exData, exData2 } = this.state;
return (
<div>
{exData}, {exData2}<br/>
<button onClick={() => this.childFunction(1)}>Click</button>
</div>
)
}
}
자식 컴포넌트에서
특정 버튼을 눌렀을 때 부모 컴포넌트의 함수를 실행하여
부모 컴포넌트의 데이터 값을 변경할 수 있는 것이다.
즉 자식 컴포넌트에서
부모 컴포넌트의 함수를 사용하여
부모 컴포넌트의 idx 값을 변경할 수 있고,
결과적으로 콘솔 창에 1이 출력되는 것이다.