React - Component Communication

React - Component Communication

Component Communication

props를 이용해서 데이터를 넘겨주는 건 많이 해봤는데… 그 반대의 경우에는 어떻게 해야할 지 잘 몰랐다. 첫 페이지에서 모달을 띄우고, Close 버튼을 누르면 모달이 보이지 않도록 해야 했는데… 아래의 코드를 참고하면 된다.

Parent -> Child

using props
class Parent extends Component {
 render() {
  return (
   <div className="parent-page">
    <Child
     value1={this.state.value1} // this
     value2={this.state.value2}
    />
   </div>
  )
 }
}

Child -> Parent

using state
  • 부모 컴포넌트에 콜백 함수 정의
  • 자식 컴포넌트에서 부모 컴포넌트에 props를 전달
class Child extends Component {
 hideModal() {
  this.setState({ showIntroModal: false });
 }
 
 render() {
  return (
   <div className="intro-page">
    {this.state.showIntroModal && (
     <Modal hideIntroModal={this.hideModal} /> // this
    )}
   </div>
  )
 }
}

class Modal extends Component {
 constructor(props) {
  super(props);

  this.close = this.close.bind(this);
 }
 
 close() {
  this.props.hideIntroModal(); // this
 }
 
 render() {
  return (
   <div className="modal-page">
    <button onClick={this.close}>Close</button>
   </div>
  )
 } 
}

참고

https://velog.io/@stellashyou/-번역-React-컴포넌트-간의-데이터-전달-방법
https://riptutorial.com/ko/reactjs/example/22703/하위-컴포넌트와-상위-컴포넌트

댓글

가장 많이 본 글