이 답변을 다시 방문하면 통신 할 수있는 두 가지 구성 요소가 필요하다고 말합니다. 이것은 이것을하기위한 평범한 반응 방법입니다. 두 개의 형제 구성 요소가있는 App
구성 요소가 하나 있습니다. props
값을 Modal 구성 요소에 전달하고 props
콜백을 해당 형제에 전달하여 모달 렌더링 또는 렌더링하지 않도록 할 수 있습니다.
class Modal extends React.Component {
render() {
return this.props.modalShow ? (
<div className="modal">
Modal loaded
</div>
) : null;
};
};
class Sibling extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.props.openModal();
}
render() {
return (
<div>
I am a sibling element.
<button onClick={this.handleClick}>Show modal</button>
</div>
)
};
}
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
modalShow: false,
};
this.openModal = this.openModal.bind(this);
};
openModal() {
this.setState({ modalShow: true });
}
render() {
return (
<div>
<Modal modalShow={this.state.modalShow} />
<Sibling openModal={this.openModal}/>
</div>
)
};
};
ReactDOM.render(
<App />,
document.getElementById('app')
);
여기서 Redux를 사용하는 것은 상태가 이미 "글로벌"이므로 훨씬 간단합니다. 그러나 아이디어는 같습니다. 부모가 상태를 제어하는 대신, 감속기와 동작 만 사용하십시오. 이게 도움이 되길 바란다.
안녕하세요, @Chris이 구현하는 방법에 대한 샘플 코드를주십시오? 미안 해요,하지만 난 아직도이게 새로운데. 감사합니다. –
더 나은 코드 예제로이 대답을 업데이트했습니다. – Chris