重温这个答案,我会说你需要有两个组件能够沟通。这是简单的React方式来做到这一点。注意有一个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